PageRenderTime 24ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

Markdown | 313 lines | 194 code | 119 blank | 0 comment | 0 complexity | 107629ea21b62754762b0f492807134e MD5 | raw file
  1. # Upgrading from 2.3.x
  2. Most of Kohana v3 works very differently from Kohana 2.3, here's a list of common gotchas and tips for upgrading.
  3. ## Naming conventions
  4. The 2.x series used suffixes to differentiate between different 'types' of class (i.e. controller, model etc.). Folders within model / controller folders didn't have any bearing on the name of the class.
  5. In 3.0 this approach has been scrapped in favour of the Zend framework filesystem conventions, where the name of the class is a path to the class itself, separated by underscores instead of slashes (i.e. `Some_Class_File` becomes `/some/class/file.php`).
  6. See the [conventions documentation](start.conventions) for more information.
  7. ## Input Library
  8. The Input Library has been removed from 3.0 in favour of just using `$_GET` and `$_POST`.
  9. Some of its features, such as [value retrieval with defaults](#post_and_get), still exist in other forms.
  10. ### XSS Protection {#xss_protection}
  11. If you need to XSS clean some user input you can use [Security::xss_clean] to sanitise it, like so:
  12. $_POST['description'] = security::xss_clean($_POST['description']);
  13. You can also use the [Security::xss_clean] as a filter with the [Validate] library:
  14. $validation = new Validate($_POST);
  15. $validate->filter('description', 'Security::xss_clean');
  16. ### POST & GET {#post_and_get}
  17. One of the great features of the Input library was that if you tried to access the value in one of the superglobal arrays and it didn't exist the Input library would return a default value that you could specify i.e.:
  18. $_GET = array();
  19. // $id is assigned the value 1
  20. $id = Input::instance()->get('id', 1);
  21. $_GET['id'] = 25;
  22. // $id is assigned the value 25
  23. $id = Input::instance()->get('id', 1);
  24. In 3.0 you can duplicate this functionality using [Arr::get]:
  25. $_GET = array();
  26. // $id is assigned the value 1
  27. $id = Arr::get($_GET, 'id', 1);
  28. $_GET['id'] = 42;
  29. // $id is assigned the value 42
  30. $id = Arr::get($_GET, 'id', 1);
  31. You can of course combine this with the [XSS protection](#xss_protection) library to sanitise your input:
  32. $input = Security::xss_clean(Arr::get($_POST, 'input', 'Default Value'));
  33. ## ORM Library
  34. There have been quite a few major changes in ORM since 2.3, here's a list of the more common upgrading problems.
  35. ### Member variables
  36. All member variables are now prefixed with an underscore (_) and are no longer accessible via `__get()`. Instead you have to call a function with the name of the property, minus the underscore.
  37. For instance, what was once `loaded` in 2.3 is now `_loaded` and can be accessed from outside the class via `$model->loaded()`.
  38. ### Relationships
  39. In 2.3 if you wanted to iterate a model's related objects you could do:
  40. foreach($model->{relation_name} as $relation)
  41. However, in the new system this won't work. In version 2.3 any queries generated using the Database library were generated in a global scope, meaning that you couldn't try and build two queries simultaneously. Take for example:
  43. This query would fail as the second, inner query would 'inherit' the conditions of the first one, thus causing pandemonia.
  44. In v3.0 this has been fixed by creating each query in its own scope, however this also means that some things won't work quite as expected. Take for example:
  45. foreach(ORM::factory('user', 3)->where('post_date', '>', time() - (3600 * 24))->posts as $post)
  46. {
  47. echo $post->title;
  48. }
  49. [!!] (See [the Database tutorial](tutorials.databases) for the new query syntax)
  50. In 2.3 you would expect this to return an iterator of all posts by user 3 where `post_date` was some time within the last 24 hours, however instead it'll apply the where condition to the user model and return a `Model_Post` with the joining conditions specified.
  51. To achieve the same effect as in 2.3 you need to rearrange the structure slightly:
  52. foreach(ORM::factory('user', 3)->posts->where('post_date', '>', time() - (36000 * 24))->find_all() as $post)
  53. {
  54. echo $post->title;
  55. }
  56. This also applies to `has_one` relationships:
  57. // Incorrect
  58. $user = ORM::factory('post', 42)->author;
  59. // Correct
  60. $user = ORM::factory('post', 42)->author->find();
  61. ### Has and belongs to many relationships
  62. In 2.3 you could specify `has_and_belongs_to_many` relationships. In 3.0 this functionality has been refactored into `has_many` *through*.
  63. In your models you define a `has_many` relationship to the other model but then you add a `'through' => 'table'` attribute, where `'table'` is the name of your through table. For example (in the context of posts<>categories):
  64. $_has_many = array
  65. (
  66. 'categories' => array
  67. (
  68. 'model' => 'category', // The foreign model
  69. 'through' => 'post_categories' // The joining table
  70. ),
  71. );
  72. If you've set up kohana to use a table prefix then you don't need to worry about explicitly prefixing the table.
  73. ### Foreign keys
  74. If you wanted to override a foreign key in 2.x's ORM you had to specify the relationship it belonged to, and your new foreign key in the member variable `$foreign_keys`.
  75. In 3.0 you now define a `foreign_key` key in the relationship's definition, like so:
  76. Class Model_Post extends ORM
  77. {
  78. $_belongs_to = array
  79. (
  80. 'author' => array
  81. (
  82. 'model' => 'user',
  83. 'foreign_key' => 'user_id',
  84. ),
  85. );
  86. }
  87. In this example we should then have a `user_id` field in our posts table.
  88. In has_many relationships the `far_key` is the field in the through table which links it to the foreign table and the foreign key is the field in the through table which links "this" model's table to the through table.
  89. Consider the following setup, "Posts" have and belong to many "Categories" through `posts_sections`.
  90. | categories | posts_sections | posts |
  91. |------------|------------------|---------|
  92. | id | section_id | id |
  93. | name | post_id | title |
  94. | | | content |
  95. Class Model_Post extends ORM
  96. {
  97. protected $_has_many = array(
  98. 'sections' => array(
  99. 'model' => 'category',
  100. 'through' => 'posts_sections',
  101. 'far_key' => 'section_id',
  102. ),
  103. );
  104. }
  105. Class Model_Category extends ORM
  106. {
  107. protected $_has_many = array (
  108. 'posts' => array(
  109. 'model' => 'post',
  110. 'through' => 'posts_sections',
  111. 'foreign_key' => 'section_id',
  112. ),
  113. );
  114. }
  115. Obviously the aliasing setup here is a little crazy, but it's a good example of how the foreign/far key system works.
  116. ### ORM Iterator
  117. It's also worth noting that `ORM_Iterator` has now been refactored into `Database_Result`.
  118. If you need to get an array of ORM objects with their keys as the object's pk, you need to call [Database_Result::as_array], e.g.
  119. $objects = ORM::factory('user')->find_all()->as_array('id');
  120. Where `id` is the user table's primary key.
  121. ## Router Library
  122. In version 2 there was a Router library that handled the main request. It let you define basic routes in a `config/routes.php` file and it would allow you to use custom regex for the routes, however it was fairly inflexible if you wanted to do something radical.
  123. ## Routes
  124. The routing system (now refered to as the request system) is a lot more flexible in 3.0. Routes are now defined in the bootstrap file (`application/bootstrap.php`) and the module init.php (`modules/module_name/init.php`). It's also worth noting that routes are evaluated in the order that they are defined.
  125. Instead of defining an array of routes you now create a new [Route] object for each route. Unlike in the 2.x series there is no need to map one uri to another. Instead you specify a pattern for a uri, use variables to mark the segments (i.e. controller, method, id).
  126. For example, in 2.x these regexes:
  127. $config['([a-z]+)/?(\d+)/?([a-z]*)'] = '$1/$3/$1';
  128. Would map the uri `controller/id/method` to `controller/method/id`. In 3.0 you'd use:
  129. Route::set('reversed','(<controller>(/<id>(/<action>)))')
  130. ->defaults(array('controller' => 'posts', 'action' => 'index'));
  131. [!!] Each uri should have be given a unique name (in this case it's `reversed`), the reasoning behind this is explained in [the url tutorial](tutorials.urls).
  132. Angled brackets denote dynamic sections that should be parsed into variables. Rounded brackets mark an optional section which is not required. If you wanted to only match uris beginning with admin you could use:
  133. Rouse::set('admin', 'admin(/<controller>(/<id>(/<action>)))');
  134. And if you wanted to force the user to specify a controller:
  135. Route::set('admin', 'admin/<controller>(/<id>(/<action>))');
  136. Optional route variables need default values in order to function correctly, you specify these as follows:
  137. Route::set('reversed','(<controller>(/<id>(/<action>)))')
  138. ->defaults(array(
  139. 'controller' => 'post',
  140. 'action' => 'list',
  141. 'id' => 1
  142. ));
  143. [!!] Kohana has only one 'default default': Kohana assumes your default 'action' is 'index' unless you tell it otherwise, you can change this super-default by setting [Route::$default_action].
  144. If you need to use custom regex for uri segments then pass an array of `segment => regex` i.e.:
  145. Route::set('reversed', '(<controller>(/<id>(/<action>)))', array('id' => '[a-z_]+'))
  146. ->defaults(array('controller' => 'posts', 'action' => 'index'))
  147. This would force the `id` value to consist of lowercase alpha characters and underscores.
  148. ### Actions
  149. One more thing we need to mention is that methods in a controller that can be accessed via the url are now called "actions", and are prefixed with 'action_'.
  150. For example, in the above routes, if the user calls `admin/posts/1/edit` then the action is `edit` but the method called on the controller will be `action_edit`. See [the url tutorial](tutorials.urls) for more info.
  151. ## Sessions
  152. There are no longer any `Session::set_flash()`, `Session::keep_flash()` or `Session::expire_flash()` methods, instead you must use [Session::get_once].
  153. ## URL Helper
  154. Only a few things have changed with the url helper
  155. * `url::redirect()` has been moved into [Request::redirect]
  156. This instance function can be accessed by `$this->request->redirect()` within controllers and `Request::instance()->redirect()` globally.
  157. * `url::current` has now been replaced with `$this->request->uri()`
  158. ## Valid / Validation
  159. These two classes have been merged into a single class called `Validate`.
  160. The syntax has also changed a little for validating arrays:
  161. $validate = new Validate($_POST);
  162. // Apply a filter to all items in the arrays
  163. $validate->filter(TRUE, 'trim');
  164. // To specify rules individually use rule()
  165. $validate
  166. ->rule('field', 'not_empty')
  167. ->rule('field', 'matches', array('another_field'));
  168. // To set multiple rules for a field use rules(), passing an array of rules => params as the second argument
  169. $validate->rules('field', array(
  170. 'not_empty' => NULL,
  171. 'matches' => array('another_field')
  172. ));
  173. The 'required' rule has also been renamed to 'not_empty' for clarity's sake.
  174. ## View Library
  175. There have been a few minor changes to the View library which are worth noting.
  176. In 2.3 views were rendered within the scope of the controller, allowing you to use `$this` as a reference to the controller within the view, this has been changed in 3.0. Views now render in an empty scope. If you need to use `$this` in your view you can bind a reference to it using [View::bind]: `$view->bind('this', $this)`.
  177. It's worth noting, though, that this is *very* bad practice as it couples your view to the controller, preventing reuse. The recommended way is to pass the required variables to the view like so:
  178. $view = View::factory('my/view');
  179. $view->variable = $this->property;
  180. // OR if you want to chain this
  181. $view
  182. ->set('variable', $this->property)
  183. ->set('another_variable', 42);
  184. // NOT Recommended
  185. $view->bind('this', $this);
  186. Because the view is rendered in an empty scope `Controller::_kohana_load_view` is now redundant. If you need to modify the view before it's rendered (i.e. to add a generate a site-wide menu) you can use [Controller::after].
  187. Class Controller_Hello extends Controller_Template
  188. {
  189. function after()
  190. {
  191. $this->template->menu = '...';
  192. return parent::after();
  193. }
  194. }