slab
文件大小: unknow
源码售价: 5 个金币 积分规则     积分充值
资源说明:PHP5 framework
# Slab

## A PHP5 framework.
Slab is/was an MVC framework inspired by CakePHP and CodeIgniter, but I actually want to move away from the strict MVC paradigm and loosen it up.


## Views

Views are PHP files that are included in the `View::__render` method. In the scope of the view a number of objects are available:

- `$this` is the `View` instance
- The `$html` and `$number` helpers
- `$pageTitle` is available, and can be set within the view, and used when rendering the layout (eg. `<?php eh($pageTitle); ?>`)
- `$dispatcher`, the request-wide `Dispatcher` instance which can be used for rendering partials/subviews: `
    dispatch("/item/view/{$id}", array('data' => $data))->render_to_string()); ?>
` - Anything set in the controller using the `set` method is first class, so if the controller action method uses `$this->set('foos', $this->fooService->get_foos());` the view will be able to do something like `...` ### Partials / subviews A partial view is produced by a controller action that returns `$this->partial()`, which is a `PartialView`. Calling `$view->render_to_string` then returns a string which can be displayed in the containing view. So I might have an item view partial in `controllers/my_item_controller.php`: function item_view($id) { $this->set('item', $this->itemService->get($id)); return $this->partial(); } The partial view itself (`views/my_item/item_view`):
  • A main view then uses the partial in a loop:

    Items:

      dispatch("/my_item/item_view/{$item['id']}")->render_to_string()); ?>
    #### Shortcut method for consuming partials `Dispatcher` includes a `partial()` method which returns the string result of the partial view. It also ensures the partial view is used by calling `$controller->partial()`. This results in a simplified shortcut method for creating and using partials. So the partial view action in `controllers/my_item_controller.php` is: function item_view($id) { $this->set('item', $this->itemService->get($id)); } The partial is used in another view as follows:

    Items:

      partial("/my_item/item_view/{$item['id']}")); ?>
    ## Models The `Model` class in Slab is a wrapper around a simple database access layer. Generally services receive an instance of the `Model` class which has been initialised with a connection to the database and the name of the underlying table. The database schema is also loaded and used to escape fields. The `Model` class then provides methods that hide some of the complexity of querying the underlying table and provide typed and parameterised `INSERT` and `UPDATE` methods. The database is never too far under the surface though: `$foos = $model->find_all_by_query("SELECT * FROM Foos WHERE name = 'Ben'")` goes straight to the database and returns an array of hash arrays: `$foos[0]['name'] == 'Ben'`. Note that if you are trying to save UTF-8 text (eg copying and pasting from MS Word which includes so-called 'smart quotes') to a database table which is set up for UTF-8 collation the site needs include this in the `head`: ... See [this StackOverflow question](http://stackoverflow.com/questions/4696499/meta-charset-utf-8-vs-meta-http-equiv-content-type) for some discussion around this issue. ### `get_last_error` Returns the last error generated in the current database connection. ### `find` / `get` / `load` `find($id = null, $fields = null)`: Find the first model using `$id` against the default primary field name. `$fields` is an optional parameter which is an array of fields to include in the resulting model. If the value for `$id` is not provided or is null, `$model->id` is used instead (**although this is not recommended and will be deprecated and removed (#16) in a future version**). ### `find_all` / `get_all` / `load_all` `find_all($conditions = null, $fields = null, $order = null)`: - `$conditions` is an optional string containing the `WHERE` clause, or an array of conditions that are `AND`ed together - `$fields` is an optional array of the field names to return - `$order` is an optional string containing the `ORDER BY` clause Both of these examples are functionally equivalent except that passing an array of conditions causes the field values to be escaped first: $things = $model->find_all("user_id = ${id} AND deleted = 0"); $things = $model->find_all(array( 'user_id' => $id, 'deleted' => false )); ### `find_all_by_query` / `get_all_by_query` / `load_all_by_query` / `query` `find_all_by_query($sql)`: directly executes the SQL on the database and returns an array of hash arrays. ### `scalar($field, $conditions = null)` Returns the specified field of the first row of the results given the conditions or null if no rows were returned. $personsModel->scalar('MAX(age)', 'deleted = 0') is roughly: SELECT MAX(age) FROM persons WHERE deleted = 0 ### `find_by` / `get_by` / `load_by` `load_by($key, $val)`: Find the first model by the given key and value. If the `$key` and `$val` are arrays they are ANDed together: `load_by(array('key1', 'key2'), array(1, '2'))`. If no results are found returns `null`. ### `find_all_by` / `get_all_by` / `load_all_by` `find_all_by($key, $val = null, $fields = null, $order = null)`: returns all models matching the given key and value. `$key` can also be an array of key/values, eg: `$model->find_all_by(array('name' => 'Ben', 'age' => '32))`. ### `find_first` / `get_first` / `load_first` `find_first($conditions = null, $fields = null, $order = null)`: returns the first model matching the criteria. `$conditions` is either a string containing the `WHERE` clause or an array of conditions that are `AND`ed together. Eg: $foo = $fooModel->find_first('age < 16', '*', 'age DESC'); // $foo is the first oldest foo under 16 $foo = $fooModel->find_first(array('age' => 65), '*', 'surname'); // $foo is the first foo aged 65 by surname ### `save` `save($data)`: saves the data to the database (in the configured table). If `$data` includes the primary field, performs an `UPDATE` otherwise performs an `INSERT` and returns the ID (the value of `mysql_insert_id()`). ### `update_field` `update_field($id, $fieldName, $fieldData)`: updates a single field to the model identified by `$id`. Eg: $pageModel->update_field(16, 'content', $newContent); ### `remove` / `del` / `delete` `remove($id)`: deletes the row with the given ID. ### `remove_all` / `del_all` / `delete_all` `remove_all($conditions = null)`: deletes all rows that meet the given conditions (either a string `WHERE` clause or an array of key/values which are `AND`ed together) or all rows if no condition is provided. ### `exists` `exists($conditions)`: returns whether one or more models exist in the database that satisfy the given conditions - either a string `WHERE` clause or an `AND`ed key/value array. ### `count` `count($conditions = null)`: returns the count of rows that satisfy the condition - either a string `WHERE` clause or an `AND`ed key/value array. ## Controllers ### Action names The action is found from the request path (`/controller/action/parameters`) and is matched to a method in the relevant controller ("dispatched"). Action names that start with double-underscores (eg. `function __authenticate() {...}`). This is to allow 'private' methods that cannot be accessed by the Slab dispatch process. Action names can start with a single underscore which is used as a convention for partial views although this is not enforced and does not add any magic functionality - any action can result in a partial response and actions starting with an underscore do not have to be partials and are not necessarily returned as partials. ### before_action / before_filter `before_action()` and `before_filter()` are called (in that order) _after_ the cookie and components are added and intialised just prior to dispatching the action method. This is a good spot to initialise any services used by the controller or to call `__authenticate()` in controllers that have security concerns. ### after_action / after_filter `after_action()` and `after_filter()` are called (in that order) immediately after calling the action method and ensuring that the view (or `actionResult`) is set. ### The SlabInternals controller `SlabInternalsController` is a special built-in controller that is used to support error handling. If you happen to create a controller path named `slab_internals` it won't be picked up by the dispatcher as it will short-circuit to the built-in controller. ### Methods available to controllers #### url Wraps `$dispatcher->url()`. #### set Sets values in the view's data: // in the controller: function action() { $this->set('items', $this->itemService->getAll()); } // in the view:
    #### set_layout($layout) Set the view's layout (calls `$this->view->set_layout()`). #### set_view($view = null, $layout = null) Sets the action result to view and optionally the layout. This is used as the default action result from an action. #### partial($view = null, $contentType = 'text/html') Sets the action result to a `PartialResult` which renders the view without a layout. #### redirect($url) Sets the action result to a `RedirectResult` which redirects the client to the specified URL using a `302 FOUND` HTTP response. #### `redirect_refresh($url)` Sets the action result to a `RedirectRefreshResult` which sets a `Refresh` HTTP header which causes a browser redirection to the specified URL. #### `text($s)` Sets the action result to a `TextResult` which just returns the given string. #### `json($o)` Sets the action result to a `JsonResult` which returns the given object as a serialised JSON string using `json_encode`. #### `file_inline($filename, $data, $encoding = 'binary')` Sets the action result to a `FileResult` which returns a file with the given filename and binary data type (by default) and an `inline` content disposition. #### `file_attachment($filename, $data, $encoding = 'binary')` Sets the action result to a `FileResult` which returns a file with the given file name and binary data type (by default) and an `attachment` content disposition. This causes the browser to open the file using the file save dialog ('What do you want to do with this file?' etc). This example assumes that you have a database table with an ID, a `name` column containing a filename, and a `data` column (`BLOB` or `LONGBLOB`, etc) containing binary data: function get_file($id) { $files = $this->dispatcher->load_model('files'); $file = $files->get($id); $this->file_attachment($file['name'], $file['data']); } // in a view, ... #### `ajax($statusCode, $data = null)` Sets the action result to an `AjaxResult` which sets the specified HTTP status code and includes the optional data in the body of the response. #### `ajax_success($data = null)` Sets the action result to an `AjaxResult` with a HTTP status code of `200 OK` and includes the optional data in the body of the response. #### `ajax_failure($data = null) / ajax_error($data = null)` Sets the action result to an `AjaxResult` with a HTTP status code of `500 Internal Server Error` and includes the optional data in the body of the response. #### `file_not_found` Sets the action result to an `AjaxResult` with a HTTP status code of `404 Not Found`. #### `action($cap, $data = null)` Executes another action (via `$this->dispatcher->dispatch($cap, $data)`) and uses the result of that action for this action (nested dispatch). #### `object_result($obj)` Sets the action result to an `ObjectResult` with the provided object data. This is not generally used for normal actions. Rather it would be used by a shared action that is only used via nested dispatch where a PHP object needs to be returned. #### `controller_result($controller)` Sets the action result to a `ControllerResult` containing the given controller (usually `$this`). This allows passing a full controller back to an action via a nested dispatch to allow really funky actions. #### `physical_file($filename)` Sets the action result to a `FileResult` containing the data read from the specified file. This is used to allow returning a physical file which would otherwise not be available via a `redirect` action. For example, returning `/etc/passwd` (which would be a **really bad idea**). #### `redirect_immediate` Dirty way of redirecting by setting the location header then calling `die()` to terminate the script. Because this bypasses the Slab lifecycle this stops cookies from being saved etc. ## Helpers Helpers are included directly in the scope of each view. There are two helpers: `$html` and `$number`. They can be used in the view like so:

    Link to HELP

    ### `HtmlHelper - $html` Most of the html methods relate to creating inputs which can be a bit verbose. These are most handy with the `select` statements where the options could come from a database, so it would save a lot of boilerplate code. The most used method is `url()`, which is the recommended method for producing a relative URL to either a controller action or a static file. #### `url` `url($u)`: Wraps `dispatcher->url` which returns either a relative path to a static file or a path to a controller action, optionally using url rewriting for pretty, SEO friendly URLs if enabled (default), optionally including a session ID if the session ID is persisted via the URL. For example, if the site is hosted at `www.domain.com/some/application/`, `url('/pages/home')` may return (depending on the environment): - `/some/application/pages/home` - `/some/application/slab.php?url=/pages/home` - `/some/application/pages/home?session_id=HASH` - `/some/application/slab.php?url=/pages/home&session_id=HASH` If there exists a file at `www.domain.com/some/application/images/header.jpg`, `url('/images/header.jpg')` would return `/some/application/images/header.jpg`. #### `markdown($markdownText)` Passes the [Markdown](http://daringfireball.net/projects/markdown/) formatted input through [Markdown Extra](http://michelf.com/projects/php-markdown/) and returns the resultant HTML. This is really cool within a view: markdown(<< Note that `$` signs need to be escaped using `\$` within PHP's [heredoc syntax](http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc). #### `label` `label($forId, $value)`: Returns a HTML `label` element. Eg.:

    label('data[name]', 'Name:')); ?>

    results in:

    #### `input_hidden` `input_hidden($params)`: returns a hidden input element. Params is an array containing optionally `name`, `id` and `value`. Eg:
    input_hidden(array( 'name' => 'data[name]', 'id' => 'name_element', 'value' => 'Steve' ))); ?>
    results in:

    本源码包内暂不包含可直接显示的源代码文件,请下载源码包。