diff --git a/sr/_static/img/basic_mvc.png b/sr/_static/img/basic_mvc.png new file mode 100644 index 0000000000..099d13461e Binary files /dev/null and b/sr/_static/img/basic_mvc.png differ diff --git a/sr/_static/img/code-coverage.png b/sr/_static/img/code-coverage.png new file mode 100644 index 0000000000..5eff05469a Binary files /dev/null and b/sr/_static/img/code-coverage.png differ diff --git a/sr/_static/img/typical-cake-request.png b/sr/_static/img/typical-cake-request.png new file mode 100644 index 0000000000..f951d36196 Binary files /dev/null and b/sr/_static/img/typical-cake-request.png differ diff --git a/sr/appendices.rst b/sr/appendices.rst new file mode 100644 index 0000000000..fa818df38c --- /dev/null +++ b/sr/appendices.rst @@ -0,0 +1,71 @@ +Appendices +########## + +Appendices contain information regarding the new features +introduced in 2.x, and the migration path from 1.3 to 2.0. + +2.4 Migration Guide +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/2-4-migration-guide + +2.3 Migration Guide +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/2-3-migration-guide + +2.2 Migration Guide +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/2-2-migration-guide + +2.1 Migration Guide +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/2-1-migration-guide + appendices/new-features-in-cakephp-2-1 + +2.0 Migration Guide +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/2-0-migration-guide + appendices/new-features-in-cakephp-2-0 + appendices/phpunit-migration-hints + +Migration from 1.2 to 1.3 +========================= + +.. toctree:: + :maxdepth: 1 + + appendices/migrating-from-cakephp-1-2-to-1-3 + appendices/new-features-in-cakephp-1-3 + +General Information +=================== + +.. toctree:: + :maxdepth: 1 + + appendices/cakephp-development-process + appendices/glossary + + +.. meta:: + :title lang=en: Appendices + :keywords lang=en: migration guide,migration path,new features,glossary diff --git a/sr/appendices/2-0-migration-guide.rst b/sr/appendices/2-0-migration-guide.rst new file mode 100644 index 0000000000..4e079c23f8 --- /dev/null +++ b/sr/appendices/2-0-migration-guide.rst @@ -0,0 +1,1292 @@ +2.0 Migration Guide +################### + +This page summarizes the changes from CakePHP 1.3 that will assist in a project +migration to 2.0, as well as for a developer reference to get up to date with +the changes made to the core since the CakePHP 1.3 branch. Be sure to read the +other pages in this guide for all the new features and API changes. + +.. tip:: + + Be sure to checkout the :ref:`upgrade-shell` included in the 2.0 core to help you + migrate your 1.3 code to 2.0. + +PHP Version Support +=================== + +CakePHP 2.x supports PHP Version 5.2.8 and above. PHP4 support has been dropped. +For developers that are still working with production PHP4 environments, the +CakePHP 1.x versions continue to support PHP4 for the lifetime of their +development and support lifetime. + +The move to PHP 5 means all methods and properties have been updated with +visibility keywords. If your code is attempting access to private or protected +methods from a public scope, you will encounter errors. + +While this does not really constitute a large framework change, it means that +access to tighter visibility methods and variables is now not possible. + +File and Folder naming +====================== + +In CakePHP 2.0 we rethought the way we are structuring our files and folders. +Given that PHP 5.3 is supporting namespaces we decided to prepare our code base +for adopting in a near future this PHP version, so we adopted the +https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md. At first +we glanced at the internal structure of CakePHP 1.3 and realized that after all +these years there was no clear organization in the files, nor did the directory +structure really hint where each file should be located. With this change we +would be allowed to experiment a little with (almost) automatic class loading +for increasing the overall framework performance. + +Biggest roadblock for achieving this was maintaining some sort of backwards +compatibility in the way the classes are loaded right now, and we definitely did +not want to become a framework of huge class prefixes, having class names like +``My_Huge_Class_Name_In_Package``. We decided adopting a strategy of keeping simple +class names while offering a very intuitive way of declaring class locations and +clear migration path for future PHP 5.3 version of CakePHP. First let's +highlight the main changes in file naming standard we adopted: + +File names +---------- + +All files containing classes should be named after the class it contains. No +file should contain more than one class. So, no more lowercasing and +underscoring your file names. Here are some examples: + +* ``my_things_controller.php`` becomes ``MyThingsController.php`` +* ``form.php`` (a Helper) becomes ``FormHelper.php`` +* ``session.php`` (a Component) becomes ``SessionComponent.php`` + +This makes file naming a lot more clear and consistent across applications, +and also avoids a few edge cases where the file loader would get confused in the +past and load files it should not. + +Folder Names +------------ + +Most folders should be also CamelCased, especially when containing classes. +Think of namespaces, each folder represents a level in the namespacing +hierarchy, folders that do not contain classes, or do not constitute a +namespace on themselves, should be lowercased. + +CamelCased Folders: + +* Config +* Console +* Controller +* Controller/Component +* Lib +* Locale +* Model +* Model/Behavior +* Plugin +* Test +* Vendor +* View +* View/Helper + +lowercased Folders: + +* tmp +* webroot + +htaccess (URL Rewriting) +=============================================== +In your ``app/webroot/.htaccess`` replace line ``RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]`` with ``RewriteRule ^(.*)$ index.php [QSA,L]`` + +AppController / AppModel / AppHelper / AppShell +=============================================== + +The ``app/app_controller.php``, ``app/app_model.php``, ``app/app_helper.php`` are now located and +named as ``app/Controller/AppController.php``, ``app/Model/AppModel.php`` and ``app/View/Helper/AppHelper.php`` respectively. + +Also all shell/task now extend AppShell. You can have your custom AppShell.php at ``app/Console/Command/AppShell.php`` + +Internationalization / Localization +=================================== + +:php:func:`__()` (Double underscore shortcut function) always returns the translation +(not echo anymore). + +If you want to echo the result of the translation, use:: + + echo __('My Message'); + +This change includes all shortcut translation methods:: + + __() + __n() + __d() + __dn() + __dc() + __dcn() + __c() + +Alongside this, if you pass additional parameters, the translation will call +`sprintf `_ with these +parameters before returning. For example:: + + // Will return something like "Called: MyClass:myMethod" + echo __('Called: %s:%s', $className, $methodName); + +It is valid for all shortcut translation methods. + +More information about the specifiers, you can see in +`sprintf `_ function. + + +Class location and constants changed +==================================== + +The constants ``APP`` and ``CORE_PATH`` +have consistent values between the web and console environments. In previous +versions of CakePHP these values changed depending on your environment. + +Basics.php +========== + +- ``getMicrotime()`` has been removed. Use the native ``microtime(true)`` + instead. +- ``e()`` was removed. Use ``echo``. +- ``r()`` was removed. Use ``str_replace``. +- ``a()`` was removed. ``Use array()`` +- ``aa()`` was removed. Use ``array()`` +- ``up()`` was removed. Use ``strtoupper()`` +- ``low()`` was removed. Use ``strtolower()`` +- ``params()`` was removed. It was not used anywhere in CakePHP. +- ``ife()`` was removed. Use a ternary operator. +- ``uses()`` was removed. Use ``App::import()`` instead. +- Compatibility functions for PHP4 have been removed. +- PHP5 constant has been removed. +- Global var called ``$TIME_START`` was removed use the constant + ``TIME_START`` or ``$_SERVER['REQUEST_TIME']`` instead. + +Removed Constants +----------------- + +A number of constants were removed, as they were no longer accurate, or +duplicated. + +* APP_PATH +* BEHAVIORS +* COMPONENTS +* CONFIGS +* CONSOLE_LIBS +* CONTROLLERS +* CONTROLLER_TESTS +* ELEMENTS +* HELPERS +* HELPER_TESTS +* LAYOUTS +* LIB_TESTS +* LIBS +* MODELS +* MODEL_TESTS +* SCRIPTS +* VIEWS + +CakeRequest +=========== + +This new class encapsulates the parameters and functions related to an incoming +request. It replaces many features inside ``Dispatcher``, +``RequestHandlerComponent`` and Controller. It also replaces +``$this->params`` array in all places. ``CakeRequest`` implements +``ArrayAccess`` so many interactions with the old params array do not need to +change. See the CakeRequest new features for more information. + +Request handling, $_GET['url'] and .htaccess files +================================================== + +CakePHP no longer uses ``$_GET['url']`` for handling application request paths. +Instead it uses ``$_SERVER['PATH_INFO']``. This provides a more uniform way of +handling requests between servers with URL rewriting and those without. Because +of these changes, you'll need to update your .htaccess files and +``app/webroot/index.php``, as these files were changed to accommodate the +changes. Additionally ``$this->params['url']['url']`` no longer exists. Instead +you should be using $this->request->url to access the same value. +This attribute now contains the url without the leading slash ``/`` prepended. + +Note: For the homepage itself (``http://domain/``) $this->request->url now returns +boolean ``false`` instead of ``/``. Make sure you check on that accordingly:: + + if (!$this->request->url) {} // instead of $this->request->url === '/' + +Components +========== + +Component is now the required base class for all components. You should update +your components and their constructors, as both have changed:: + + class PrgComponent extends Component { + public function __construct(ComponentCollection $collection, + $settings = array()) { + parent::__construct($collection, $settings); + } + } + +As with helpers it is important to call ``parent::__construct()`` in components with +overridden constructors. Settings for a component are also passed into the +constructor now, and not the ``initialize()`` callback. This makes getting well +constructed objects easier, and allows the base class to handle setting the +properties up. + +Since settings have been moved to the component constructor, the +``initialize()`` callback no longer receives ``$settings`` as its 2nd parameter. +You should update your components to use the following method signature:: + + public function initialize(Controller $controller) { } + +Additionally, the initialize() method is only called on components that are +enabled. This usually means components that are directly attached to the +controller object. + +Deprecated callbacks removed +---------------------------- + +All the deprecated callbacks in Component have not been transferred to +ComponentCollection. Instead you should use the `trigger()` method to interact +with callbacks. If you need to trigger a callback you could do so by calling:: + + $this->Components->trigger('someCallback', array(&$this)); + +Changes in disabling components +------------------------------- + +In the past you were able to disable components via `$this->Auth->enabled = +false;` for example. In CakePHP 2.0 you should use the ComponentCollection's +disable method, `$this->Components->disable('Auth');`. Using the enabled +property will not work. + +AclComponent +------------ + +- ``AclComponent`` implementations are now required to implement + ``AclInterface``. +- ``AclComponent::adapter()`` has been added to allow runtime modification of + the ``ACL`` implementation the component uses. +- ``AclComponent::grant()`` has been deprecated, it will be removed in a future + version. Use ``AclComponent::allow()`` instead. +- ``AclComponent::revoke()`` has been deprecated, it will be removed in a + future version. Use AclComponent::deny() instead. + +RequestHandlerComponent +----------------------- + +Many of RequestHandlerComponent's methods are just proxies for ``CakeRequest`` +methods. The following methods have been deprecated and will be removed in +future versions: + +- ``isSsl()`` +- ``isAjax()`` +- ``isPost()`` +- ``isPut()`` +- ``isFlash()`` +- ``isDelete()`` +- ``getReferer()`` +- ``getClientIp()`` +- ``accepts()``, ``prefers()``, ``requestedWith()`` All deal in mapped content + types now. They no longer work with mime-types. You can use + ``RequestHandler::setContent()`` to create new content types. +- ``RequestHandler::setContent()`` no longer accepts an array as a single + argument, you must supply both arguments. + +SecurityComponent +----------------- + +SecurityComponent no longer handles Basic and Digest Authentication. These are +both handled by the new AuthComponent. The following methods have been removed +from SecurityComponent: + +- requireLogin() +- generateDigestResponseHash() +- loginCredentials() +- loginRequest() +- parseDigestAuthData() + +In addition the following properties were removed: + +- $loginUsers +- $requireLogin + +Moving these features to AuthComponent was done to provide a single place for +all types of authentication and to streamline the roles of each component. + +AuthComponent +------------- + +The AuthComponent was entirely re-factored for 2.0, this was done to help reduce +developer confusion and frustration. In addition, AuthComponent was made more +flexible and extensible. You can find out more in +the :doc:`/core-libraries/components/authentication` guide. + +EmailComponent +-------------- + +The EmailComponent has been deprecated and has created a new library class to +send e-mails. See :doc:`/core-utility-libraries/email` Email changes for more details. + +SessionComponent +---------------- + +Session component has lost the following methods. + +* activate() +* active() +* __start() + +cakeError removed +================= + +The ``cakeError()`` method has been removed. It's recommended that you switch all +uses of ``cakeError`` to use exceptions. ``cakeError`` was removed because it +was simulating exceptions. Instead of simulation, real exceptions are used in +CakePHP 2.0. + +Error handling +============== + +The error handling implementation has dramatically changed in 2.0. Exceptions +have been introduced throughout the framework, and error handling has been +updated to offer more control and flexibility. You can read more in the +:doc:`/development/exceptions` and :doc:`/development/errors` section. + +Lib classes +=========== + +App +--- + +The API for ``App::build()`` has changed to ``App::build($paths, $mode).`` It +now allows you to either append, prepend or reset/replace existing paths. The +$mode param can take any of the following 3 values: App::APPEND, +App::PREPEND, ``App::RESET``. The default behavior of the function remains the +same (ie. Prepending new paths to existing list). + +App::path() +~~~~~~~~~~~ + +* Now supports plugins, App::path('Controller', 'Users') will return the folder + location of the controllers in the Users plugin. +* Won't merge core paths anymore, it will + only return paths defined in App::build() or default ones in app (or + corresponding plugin). + +App::build() +~~~~~~~~~~~~ + +* Will not merge app path with core paths anymore. + +App::objects() +~~~~~~~~~~~~~~ + +* Now supports plugins, App::objects('Users.Model') will return the models in + plugin Users. +* Returns array() instead of false for empty results or invalid types. +* Does not return core objects anymore, App::objects('core') will return array(). +* Returns the complete class name. + +App class lost the following properties, use method App::path() to access their value + +* App::$models +* App::$behaviors +* App::$controllers +* App::$components +* App::$datasources +* App::$libs +* App::$views +* App::$helpers +* App::$plugins +* App::$vendors +* App::$locales +* App::$shells + +App::import() +~~~~~~~~~~~~~ + +* No longer looks for classes recursively, it strictly uses the values for the + paths defined in App::build(). +* Will not be able to load App::import('Component', 'Component') use + App::uses('Component', 'Controller'); +* Using App::import('Lib', 'CoreClass') to load core classes is no longer + possible. +* Importing a non-existent file, supplying a wrong type or package name, or null + values for $name and $file parameters will result in a false return value. +* App::import('Core', 'CoreClass') is no longer supported, use App::uses() + instead and let the class autoloading do the rest. +* Loading Vendor files does not look recursively in the vendors folder, it will + also no longer convert the file to underscored as it did in the past. + +App::core() +~~~~~~~~~~~ + +* First parameter is no longer optional, it will always return one path +* It can't be used anymore to get the vendors paths +* It will only accept new style package names + +Class loading with App::uses() +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Although there has been a huge refactoring in how the classes are loaded, in very +few occasions you will need to change your application code to respect the way you were +used to doing it. The biggest change is the introduction of a new method:: + + App::uses('AuthComponent', 'Controller/Component'); + +We decided the function name should emulate PHP 5.3's ``use`` keyword, just as a way +of declaring where a class name should be located. The first parameter of +:php:meth:`App::uses()` is the complete name of the class you intend to load, +and the second one, the package name (or namespace) where it belongs to. The +main difference with CakePHP 1.3's :php:meth:`App::import()` is that the former +won't actually import the class, it will just setup the system so when the class +is used for the first time it will be located. + +Some examples on using :php:meth:`App::uses()` when migrating from +:php:meth:`App::import()`:: + + App::import('Controller', 'Pages'); + // becomes + App::uses('PagesController', 'Controller'); + + App::import('Component', 'Auth'); + // becomes + App::uses('AuthComponent', 'Controller/Component'); + + App::import('View', 'Media'); + // becomes + App::uses('MediaView', 'View'); + + App::import('Core', 'Xml'); + // becomes + App::uses('Xml', 'Utility'); + + App::import('Datasource', 'MongoDb.MongoDbSource'); + // becomes + App::uses('MongoDbSource', 'MongoDb.Model/Datasource'); + +All classes that were loaded in the past using ``App::import('Core', $class);`` +will need to be loaded using ``App::uses()`` referring to the correct package. +See the API to locate the classes in their new folders. Some examples:: + + App::import('Core', 'CakeRoute'); + // becomes + App::uses('CakeRoute', 'Routing/Route'); + + App::import('Core', 'Sanitize'); + // becomes + App::uses('Sanitize', 'Utility'); + + App::import('Core', 'HttpSocket'); + // becomes + App::uses('HttpSocket', 'Network/Http'); + +In contrast to how :php:meth:`App::import()` worked in the past, the new class +loader will not locate classes recursively. This led to an impressive +performance gain even on develop mode, at the cost of some seldom used features +that always caused side effects. To be clear again, the class loader will only +fetch the class in the exact package in which you told it to find it. + +App::build() and core paths +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:php:meth:`App::build()` will not merge app paths with core paths anymore. + +Examples:: + + App::build(array('controllers' => array('/full/path/to/controllers'))); + //becomes + App::build(array('Controller' => array('/full/path/to/Controller'))); + + App::build(array('helpers' => array('/full/path/to/controllers'))); + //becomes + App::build(array('View/Helper' => array('/full/path/to/View/Helper'))); + +CakeLog +------- + +- Log streams now need to implement :php:class:`CakeLogInterface`. Exceptions will be raised + if a configured logger does not. + +Cache +----- + +- :php:class:`Cache` is now a static class, it no longer has a getInstance() method. +- CacheEngine is now an abstract class. You cannot directly create instances of + it anymore. +- CacheEngine implementations must extend CacheEngine, exceptions will be + raised if a configured class does not. +- FileCache now requires trailing slashes to be added to the path setting when + you are modifying a cache configuration. +- Cache no longer retains the name of the last configured cache engine. This + means that operations you want to occur on a specific engine need to have the + $config parameter equal to the config name you want the operation to occur + on. + +:: + + Cache::config('something'); + Cache::write('key', $value); + + // would become + Cache::write('key', $value, 'something'); + +Router +------ + +- You can no longer modify named parameter settings with + ``Router::setRequestInfo()``. You should use ``Router::connectNamed()`` to + configure how named parameters are handled. +- Router no longer has a ``getInstance()`` method. It is a static class, call + its methods and properties statically. +- ``Router::getNamedExpressions()`` is deprecated. Use the new router + constants. ``Router::ACTION``, ``Router::YEAR``, ``Router::MONTH``, + ``Router::DAY``, ``Router::ID``, and ``Router::UUID`` instead. +- ``Router::defaults()`` has been removed. Delete the core routes file + inclusion from your applications routes.php file to disable default routing. + Conversely if you want default routing, you will have to add an include to + ``Cake/Config/routes.php`` in your routes file. +- When using Router::parseExtensions() the extension parameter is no longer + under ``$this->params['url']['ext']``. Instead it is available at + ``$this->request->params['ext']``. +- Default plugin routes have changed. Plugin short routes are no longer built + in for any actions other than index. Previously ``/users`` and ``/users/add`` + would map to the UsersController in the Users plugin. In 2.0, only the + ``index`` action is given a short route. If you wish to continue using short + routes, you can add a route like:: + + Router::connect( + '/users/:action', + array('controller' => 'users', 'plugin' => 'users') + ); + + To your routes file for each plugin you need short routes on. + +Your app/Config/routes.php file needs to be updated adding this line at the bottom of the file:: + + require CAKE . 'Config' . DS . 'routes.php'; + +This is needed in order to generate the default routes for your application. If you do not wish to have such routes, +or want to implement your own standard you can include your own file with custom router rules. + +Dispatcher +---------- + +- Dispatcher has been moved inside of cake/libs, you will have to update your + ``app/webroot/index.php`` file. +- ``Dispatcher::dispatch()`` now takes two parameters. The request and + response objects. These should be instances of ``CakeRequest`` & + ``CakeResponse`` or a subclass thereof. +- ``Dispatcher::parseParams()`` now only accepts a ``CakeRequest`` object. +- ``Dispatcher::baseUrl()`` has been removed. +- ``Dispatcher::getUrl()`` has been removed. +- ``Dispatcher::uri()`` has been removed. +- ``Dispatcher::$here`` has been removed. + +Configure +--------- + +- ``Configure::read()`` with no parameter no longer returns the value of + 'debug' instead it returns all values in Configure. Use + ``Configure::read('debug');`` if you want the value of debug. +- ``Configure::load()`` now requires a ConfigReader to be setup. Read + :ref:`loading-configuration-files` for more information. +- ``Configure::store()`` now writes values to a given Cache configuration. Read + :ref:`loading-configuration-files` for more information. + +Scaffold +-------- + +- Scaffold 'edit' views should be renamed to 'form'. This was done to make + scaffold and bake templates consistent. + + - ``views/scaffolds/edit.ctp`` -> ``View/Scaffolds/form.ctp`` + - ``views/posts/scaffold.edit.ctp`` -> ``View/Posts/scaffold.form.ctp`` + +Xml +--- + +- The class Xml was completely re-factored. Now this class does not manipulate + data anymore, and it is a wrapper to SimpleXMLElement. You can use the following + methods: + + - ``Xml::build()``: static method that you can pass an xml string, array, path + to file or url. The result will be a SimpleXMLElement instance or an + exception will be thrown in case of error. + - ``Xml::fromArray():`` static method that returns a SimpleXMLElement from an + array. + - ``Xml::toArray()``: static method that returns an array from + SimpleXMLElement. + +You should see the :php:class:`Xml` documentation for more information on the changes made to +the Xml class. + +Inflector +--------- + +- Inflector no longer has a ``getInstance()`` method. +- ``Inflector::slug()`` no longer supports the $map argument. Use + ``Inflector::rules()`` to define transliteration rules. + +CakeSession +----------- + +CakeSession is now a fully static class, both ``SessionHelper`` and +``SessionComponent`` are wrappers and sugar for it. It can now easily be used +in models or other contexts. All of its methods are called statically. + +Session configuration has also changed :doc:`see the session section for more +information ` + +HttpSocket +---------- + +- HttpSocket doesn't change the header keys. Following other places in core, + the HttpSocket does not change the headers. :rfc:`2616` says that headers are case + insensitive, and HttpSocket preserves the values the remote host sends. +- HttpSocket returns responses as objects now. Instead of arrays, HttpSocket + returns instances of HttpResponse. See the :php:class:`HttpSocket` + documentation for more information. +- Cookies are stored internally by host, not per instance. This means that, if + you make two requests to different servers, cookies from domain1 won't be sent + to domain2. This was done to avoid possible security problems. + + +Helpers +======= + +Constructor changed +------------------- + +In order to accommodate View being removed from the ClassRegistry, the signature +of Helper::__construct() was changed. You should update any subclasses to use +the following:: + + public function __construct(View $View, $settings = array()) + +When overriding the constructor you should always call `parent::__construct` as +well. `Helper::__construct` stores the view instance at `$this->_View` for +later reference. The settings are not handled by the parent constructor. + +HelperCollection added +---------------------- + +After examining the responsibilities of each class involved in the View layer, +it became clear that View was handling much more than a single task. The +responsibility of creating helpers is not central to what View does, and was +moved into HelperCollection. HelperCollection is responsible for loading and +constructing helpers, as well as triggering callbacks on helpers. By default, +View creates a HelperCollection in its constructor, and uses it for subsequent +operations. The HelperCollection for a view can be found at `$this->Helpers` + +The motivations for refactoring this functionality came from a few issues. + +* View being registered in ClassRegistry could cause registry poisoning issues + when requestAction or the EmailComponent were used. +* View being accessible as a global symbol invited abuse. +* Helpers were not self contained. After constructing a helper, you had to + manually construct several other objects in order to get a functioning object. + +You can read more about HelperCollection in the +:doc:`/core-libraries/collections` documentation. + +Deprecated properties +--------------------- + +The following properties on helpers are deprecated, you should use the request +object properties or Helper methods instead of directly accessing these +properties as they will be removed in a future release. + +- ``Helper::$webroot`` is deprecated, use the request object's webroot + property. +- ``Helper::$base`` is deprecated, use the request object's base property. +- ``Helper::$here`` is deprecated, use the request object's here property. +- ``Helper::$data`` is deprecated, use the request object's data property. +- ``Helper::$params`` is deprecated, use the ``$this->request`` instead. + +XmlHelper, AjaxHelper and JavascriptHelper removed +-------------------------------------------------- + +The AjaxHelper and JavascriptHelper have been removed as they were deprecated in +version 1.3. The XmlHelper was removed, as it was made obsolete and redundant +with the improvements to :php:class:`Xml`. The ``Xml`` class should be used to +replace previous usage of XmlHelper. + +The AjaxHelper, and JavascriptHelper are replaced with the JsHelper and HtmlHelper. + +JsHelper +-------- + +- ``JsBaseEngineHelper`` is now abstract, you will need to implement all the + methods that previously generated errors. + +PaginatorHelper +--------------- + +- ``PaginatorHelper::sort()`` now takes the title and key arguments in the + reverse order. $key will always be first now. This was done to prevent + needing to swap arguments when adding a second one. +- PaginatorHelper had a number of changes to the paging params used internally. + The default key has been removed. +- PaginatorHelper now supports generating links with paging parameters in the + querystring. + +There have been a few improvements to pagination in general. For more +information on that you should read the new pagination features page. + +FormHelper +---------- + +$selected parameter removed +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``$selected`` parameter was removed from several methods in ``FormHelper``. +All methods now support a ``$attributes['value']`` key now which should be used +in place of ``$selected``. This change simplifies the ``FormHelper`` methods, +reducing the number of arguments, and reduces the duplication that ``$selected`` +created. The effected methods are: + +- FormHelper::select() +- FormHelper::dateTime() +- FormHelper::year() +- FormHelper::month() +- FormHelper::day() +- FormHelper::hour() +- FormHelper::minute() +- FormHelper::meridian() + +Default URLs on forms is the current action +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The default url for all forms, is now the current url including passed, named, +and querystring parameters. You can override this default by supplying +``$options['url']`` in the second parameter of ``$this->Form->create()``. + +FormHelper::hidden() +~~~~~~~~~~~~~~~~~~~~ + +Hidden fields no longer remove the class attribute. This means that if there are +validation errors on hidden fields, the ``error-field`` class name will be +applied. + +CacheHelper +----------- + +CacheHelper has been fully decoupled from View, and uses helper callbacks to +generate caches. You should remember to place CacheHelper after other helpers +that modify content in their ``afterRender`` and ``afterLayout`` callbacks. If +you don't some changes will not be part of the cached content. + +CacheHelper also no longer uses ```` to indicate un-cached +regions. Instead it uses special HTML/XML comments. ```` and +````. This helps CacheHelper generate valid markup and still +perform the same functions as before. You can read more CacheHelper and View +changes. + +Helper Attribute format more flexible +------------------------------------- + +The Helper class has more 3 protected attributes: + +* ``Helper::_minimizedAttributes``: array with minimized attributes (ie: + ``array('checked', 'selected', ...)``); +* ``Helper::_attributeFormat``: how attributes will be generated (ie: + ``%s="%s"``); +* ``Helper::_minimizedAttributeFormat``: how minimized attributes will be + generated: (ie ``%s="%s"``) + +By default the values used in CakePHP 1.3 were not changed. But now you can +use boolean attributes from HTML, like ````. To +this, just change ``$_minimizedAttributeFormat`` in your AppHelper to ``%s``. + +To use with Html/Form helpers and others, you can write:: + + $this->Form->checkbox('field', array('checked' => true, 'value' => 'some_value')); + +Other facility is that minimized attributes can be passed as item and not as +key. For example:: + + $this->Form->checkbox('field', array('checked', 'value' => 'some_value')); + +Note that ``checked`` have a numeric key. + +Controller +========== + +- Controller's constructor now takes two parameters. A CakeRequest, and + CakeResponse objects. These objects are used to populate several deprecated + properties and will be set to $request and $response inside the controller. +- ``Controller::$webroot`` is deprecated, use the request object's webroot + property. +- ``Controller::$base`` is deprecated, use the request object's base property. +- ``Controller::$here`` is deprecated, use the request object's here property. +- ``Controller::$data`` is deprecated, use the request object's data property. +- ``Controller::$params`` is deprecated, use the ``$this->request`` instead. +- ``Controller::$Component`` has been moved to ``Controller::$Components``. See + the :doc:`/core-libraries/collections` documentation for more information. +- ``Controller::$view`` has been renamed to ``Controller::$viewClass``. + ``Controller::$view`` is now used to change which view file is rendered. +- ``Controller::render()`` now returns a CakeResponse object. + +The deprecated properties on Controller will be accessible through a ``__get()`` +method. This method will be removed in future versions, so it's recommended that +you update your application. + +Controller now defines a maxLimit for pagination. This maximum limit is set to +100, but can be overridden in the $paginate options. + + +Pagination +---------- + +Pagination has traditionally been a single method in Controller, this created a +number of problems though. Pagination was hard to extend, replace, or modify. For +2.0 pagination has been extracted into a component. :php:meth:`Controller::paginate()` still +exists, and serves as a convenience method for loading and using the +:php:class:`PaginatorComponent`. + +For more information on the new features offered by pagination in 2.0, see the +:doc:`/core-libraries/components/pagination` documentation. + +View +==== + +View no longer registered in ClassRegistry +------------------------------------------ + +The view being registered ClassRegistry invited abuse and affectively created a +global symbol. In 2.0 each Helper receives the current `View` instance in its +constructor. This allows helpers access to the view in a similar fashion as in +the past, without creating global symbols. You can access the view instance at +`$this->_View` in any helper. + +Deprecated properties +--------------------- + +- ``View::$webroot`` is deprecated, use the request object's webroot property. +- ``View::$base`` is deprecated, use the request object's base property. +- ``View::$here`` is deprecated, use the request object's here property. +- ``View::$data`` is deprecated, use the request object's data property. +- ``View::$params`` is deprecated, use the ``$this->request`` instead. +- ``View::$loaded`` has been removed. Use the ``HelperCollection`` to access + loaded helpers. +- ``View::$model`` has been removed. This behavior is now on :php:class:`Helper` +- ``View::$modelId`` has been removed. This behavior is now on + :php:class:`Helper` +- ``View::$association`` has been removed. This behavior is now on + :php:class:`Helper` +- ``View::$fieldSuffix`` has been removed. This behavior is now on + :php:class:`Helper` +- ``View::entity()`` has been removed. This behavior is now on + :php:class:`Helper` +- ``View::_loadHelpers()`` has been removed, used ``View::loadHelpers()`` + instead. +- How ``View::element()`` uses caching has changed, see below for more + information. +- View callbacks have been shifted around, see below for more information +- API for ``View::element()`` has changed. Read here for more info. + +The deprecated properties on View will be accessible through a ``__get()`` +method. This method will be removed in future versions, so it's recommended that +you update your application. + +Removed methods +--------------- + +* ``View::_triggerHelpers()`` Use ``$this->Helpers->trigger()`` instead. +* ``View::_loadHelpers()`` Use ``$this->loadHelpers()`` instead. Helpers now lazy + load their own helpers. + +Added methods +------------- + +* ``View::loadHelper($name, $settings = array());`` Load a single helper. +* ``View::loadHelpers()`` Loads all the helpers indicated in ``View::$helpers``. + +View->Helpers +------------- + +By default View objects contain a :php:class:`HelperCollection` at ``$this->Helpers``. + +Themes +------ + +To use themes in your Controller you no longer set ``public $view = 'Theme';``. +Use ``public $viewClass = 'Theme';`` instead. + +Callback positioning changes +---------------------------- + +beforeLayout used to fire after scripts_for_layout and content_for_layout were +prepared. In 2.0, beforeLayout is fired before any of the special variables are +prepared, allowing you to manipulate them before they are passed to the layout. +The same was done for beforeRender. It is now fired well before any view +variables are manipulated. In addition to these changes, helper callbacks always +receive the name of the file about to be rendered. This combined with helpers +being able to access the view through ``$this->_View`` and the current view +content through ``$this->_View->output`` gives you more power than ever before. + +Helper callback signature changes +--------------------------------- + +Helper callbacks now always get one argument passed in. For beforeRender and +afterRender it is the view file being rendered. For beforeLayout and afterLayout +it is the layout file being rendered. Your helpers function signatures should +look like:: + + public function beforeRender($viewFile) { + + } + + public function afterRender($viewFile) { + + } + + public function beforeLayout($layoutFile) { + + } + + public function afterLayout($layoutFile) { + + } + + +Element caching, and view callbacks have been changed in 2.0 to help provide you +with more flexibility and consistency. :doc:`Read more about those +changes `. + +CacheHelper decoupled +--------------------- + +In previous versions there was a tight coupling between :php:class:`CacheHelper` +and :php:class:`View`. For 2.0 this coupling has been removed and CacheHelper +just uses callbacks like other helpers to generate full page caches. + + +CacheHelper ```` tags changed +------------------------------------------- + +In previous versions, CacheHelper used a special ```` tag as +markers for output that should not be part of the full page cache. These tags +were not part of any XML schema, and were not possible to validate in HTML or +XML documents. For 2.0, these tags have been replaced with HTML/XML comments:: + + becomes + becomes + +The internal code for full page view caches has also changed, so be sure to +clear out view cache files when updating. + +MediaView changes +----------------- + +:php:func:`MediaView::render()` now forces download of unknown file types +instead of just returning false. If you want you provide an alternate download +filename you now specify the full name including extension using key 'name' in +the array parameter passed to the function. + + +PHPUnit instead of SimpleTest +============================= + +All of the core test cases and supporting infrastructure have been ported to use +PHPUnit 3.5. Of course you can continue to use SimpleTest in your application by +replacing the related files. No further support will be given for SimpleTest and +it is recommended that you migrate to PHPUnit as well. For some additional +information on how to migrate your tests see PHPUnit migration hints. + +No more group tests +------------------- + +PHPUnit does not differentiate between group tests and single test cases in the +runner. Because of this, the group test options, and support for old style group +tests has been removed. It is recommended that GroupTests be ported to +``PHPUnit_Framework_Testsuite`` subclasses. You can find several examples of this +in CakePHP's test suite. Group test related methods on ``TestManager`` have also +been removed. + +Testsuite shell +--------------- + +The testsuite shell has had its invocation simplified and expanded. You no +longer need to differentiate between ``case`` and ``group``. It is assumed that +all tests are cases. In the past you would have done +``cake testsuite app case models/post`` you can now do ``cake testsuite app +Model/Post``. + + +The testsuite shell has been refactored to use the PHPUnit cli tool. It now +supports all the command line options supported by PHPUnit. +``cake testsuite help`` will show you a list of all possible modifiers. + +Models +====== + +Model relationships are now lazy loaded. You can run into a situation where +assigning a value to a nonexistent model property will throw errors:: + + $Post->inexistentProperty[] = 'value'; + +will throw the error "Notice: Indirect modification of overloaded property +$inexistentProperty has no effect". Assigning an initial value to the property +solves the issue:: + + $Post->nonexistentProperty = array(); + $Post->nonexistentProperty[] = 'value'; + +Or just declare the property in the model class:: + + class Post { + public $nonexistentProperty = array(); + } + +Either of these approaches will solve the notice errors. + +The notation of ``find()`` in CakePHP 1.2 is no longer supported. Finds should use +notation ``$model->find('type', array(PARAMS))`` in CakePHP 1.3. + +- ``Model::$_findMethods`` is now ``Model::$findMethods``. This property is now + public and can be modified by behaviors. + + + +Database objects +---------------- + +CakePHP 2.0 introduces some changes to Database objects that should not greatly +affect backwards compatibility. The biggest one is the adoption of PDO for +handling database connections. If you are using a vanilla installation of PHP 5 +you will already have installed the needed extensions, but you may need to +activate individual extensions for each driver you wish to use. + +Using PDO across all DBOs let us homogenize the code for each one and provide +more reliable and predictable behavior for all drivers. It also allowed us to +write more portable and accurate tests for database related code. + +The first thing users will probably miss is the "affected rows" and "total rows" +statistics, as they are not reported due to the more performant and lazy design +of PDO, there are ways to overcome this issue but very specific to each +database. Those statistics are not gone, though, but could be missing or even +inaccurate for some drivers. + +A nice feature added after the PDO adoption is the ability to use prepared +statements with query placeholders using the native driver if available. + +List of Changes +~~~~~~~~~~~~~~~ + +* DboMysqli was removed, we will support DboMysql only. +* API for DboSource::execute has changed, it will now take an array of query + values as second parameter:: + + public function execute($sql, $params = array(), $options = array()) + + became:: + + public function execute($sql, $options = array(), $params = array()) + + third parameter is meant to receive options for logging, currently it only + understands the "log" option. + +* DboSource::value() looses its third parameter, it was not used anyways +* DboSource::fetchAll() now accepts an array as second parameter, to pass values + to be bound to the query, third parameter was dropped. Example:: + + $db->fetchAll( + 'SELECT + * from users + WHERE + username = ? + AND + password = ?', + array('jhon', '12345') + ); + $db->fetchAll( + 'SELECT + * from users + WHERE + username = :username + AND + password = :password', + array('username' => 'jhon', 'password' => '12345') + ); + +The PDO driver will automatically escape those values for you. + +* Database statistics are collected only if the "fullDebug" property of the + corresponding DBO is set to true. +* New method DboSource::getConnection() will return the PDO object in case you + need to talk to the driver directly. +* Treatment of boolean values changed a bit to make it more cross-database + friendly, you may need to change your test cases. +* Postgresql support was immensely improved, it now correctly creates schemas, + truncate tables, and is easier to write tests using it. +* DboSource::insertMulti() will no longer accept sql string, just pass an array + of fields and a nested array of values to insert them all at once +* TranslateBehavior was refactored to use model virtualFields, this makes the + implementation more portable. +* All tests cases with Mysql related stuff were moved to the corresponding + driver test case. This left the DboSourceTest file a bit skinny. +* Transaction nesting support. Now it is possible to start a transaction several + times. It will only be committed if the commit method is called the same + amount of times. +* Sqlite support was greatly improved. The major difference with cake 1.3 is + that it will only support Sqlite 3.x . It is a great alternative for + development apps, and quick at running test cases. +* Boolean column values will be casted to php native boolean type automatically, + so make sure you update your test cases and code if you were expecting the + returned value to be a string or an integer: If you had a "published" column in + the past using mysql all values returned from a find would be numeric in the + past, now they are strict boolean values. + +Behaviors +========= + +BehaviorCollection +------------------ + +- ``BehaviorCollection`` no longer ``strtolower()'s`` mappedMethods. Behavior + mappedMethods are now case sensitive. + +AclBehavior and TreeBehavior +---------------------------- + +- No longer supports strings as configuration. Example:: + + public $actsAs = array( + 'Acl' => 'Controlled', + 'Tree' => 'nested' + ); + + became:: + + public $actsAs = array( + 'Acl' => array('type' => 'Controlled'), + 'Tree' => array('type' => 'nested') + ); + + +Plugins +======= + +Plugins no longer magically append their plugin prefix to components, helpers +and models used within them. You must be explicit with the components, models, +and helpers you wish to use. In the past:: + + public $components = array('Session', 'Comments'); + +Would look in the controller's plugin before checking app/core components. It +will now only look in the app/core components. If you wish to use objects from a +plugin you must put the plugin name:: + + public $components = array('Session', 'Comment.Comments'); + +This was done to reduce hard to debug issues caused by magic misfiring. It also +improves consistency in an application, as objects have one authoritative way to +reference them. + +Plugin App Controller and Plugin App Model +------------------------------------------ + +The plugin AppController and AppModel are no longer located directly in the +plugin folder. They are now placed into the plugin's Controller and Model +folders as such:: + + /app + /Plugin + /Comment + /Controller + CommentAppController.php + /Model + CommentAppModel.php + +Console +======= + +Much of the console framework was rebuilt for 2.0 to address many of the +following issues: + +- Tightly coupled. +- It was difficult to make help text for shells. +- Parameters for shells were tedious to validate. +- Plugin tasks were not reachable. +- Objects with too many responsibilities. + +Backwards incompatible Shell API changes +---------------------------------------- + +- ``Shell`` no longer has an ``AppModel`` instance. This ``AppModel`` instance + was not correctly built and was problematic. +- ``Shell::_loadDbConfig()`` has been removed. It was not generic enough to + stay in Shell. You can use the ``DbConfigTask`` if you need to ask the user + to create a db config. +- Shells no longer use ``$this->Dispatcher`` to access stdin, stdout, and + stderr. They have ``ConsoleOutput`` and ``ConsoleInput`` objects to handle + that now. +- Shells lazy load tasks, and use ``TaskCollection`` to provide an interface + similar to that used for Helpers, Components, and Behaviors for on the fly + loading of tasks. +- ``Shell::$shell`` has been removed. +- ``Shell::_checkArgs()`` has been removed. Configure a ``ConsoleOptionParser`` +- Shells no longer have direct access to ``ShellDispatcher``. You should use + the ``ConsoleInput``, and ``ConsoleOutput`` objects instead. If you need to + dispatch other shells, see the section on 'Invoking other shells from your + shell'. + +Backwards incompatible ShellDispatcher API changes +-------------------------------------------------- + +- ``ShellDispatcher`` no longer has stdout, stdin, stderr file handles. +- ``ShellDispatcher::$shell`` has been removed. +- ``ShellDispatcher::$shellClass`` has been removed. +- ``ShellDispatcher::$shellName`` has been removed. +- ``ShellDispatcher::$shellCommand`` has been removed. +- ``ShellDispatcher::$shellPaths`` has been removed, use + ``App::path('shells');`` instead. +- ``ShellDispatcher`` no longer uses 'help' as a magic method that has special + status. Instead use the ``--help/-h`` options, and an option parser. + +Backwards incompatible Shell Changes +------------------------------------ + +- Bake's ControllerTask no longer takes ``public`` and ``admin`` as passed + arguments. They are now options, indicated like ``--admin`` and ``--public``. + +It's recommended that you use the help on shells you use to see what if any +parameters have changed. It's also recommended that you read the console new +features for more information on new APIs that are available. + +Debugging +========= + +The ``debug()`` function now defaults to outputting HTML safe strings. This is +disabled if being used in the console. The ``$showHtml`` option for ``debug()`` +can be set to false to disable HTML-safe output from debug. + +ConnectionManager +================= + +``ConnectionManager::enumConnectionObjects()`` will now return the current +configuration for each connection created, instead of an array with filename, +class name and plugin, which wasn't really useful. + +When defining database connections you will need to make some changes to the way +configs were defined in the past. Basically in the database configuration class, +the key "driver" is not accepted anymore, only "datasource", in order to make it +more consistent. Also, as the datasources have been moved to packages you will +need to pass the package they are located in. Example:: + + public $default = array( + 'datasource' => 'Database/Mysql', + 'persistent' => false, + 'host' => 'localhost', + 'login' => 'root', + 'password' => 'root', + 'database' => 'cake', + ); + + +.. meta:: + :title lang=en: 2.0 Migration Guide + :description lang=en: This page summarizes the changes from CakePHP 1.3 that will assist in a project migration to 2.0, as well as for a developer reference to get up to date with the changes made to the core since the CakePHP 1.3 branch. + :keywords lang=en: cakephp upgrade,cakephp migration,migration guide,1.3 to 2.0,update cakephp,backwards compatibility,api changes,x versions,directory structure,new features diff --git a/sr/appendices/2-1-migration-guide.rst b/sr/appendices/2-1-migration-guide.rst new file mode 100644 index 0000000000..759be4a36c --- /dev/null +++ b/sr/appendices/2-1-migration-guide.rst @@ -0,0 +1,363 @@ +2.1 Migration Guide +################### + +CakePHP 2.1 is a fully API compatible upgrade from 2.0. This page outlines the +changes and improvements made for 2.1. + +AppController, AppHelper, AppModel and AppShell +=============================================== + +These classes are now required to be part of the app directory, as they were +removed from the CakePHP core. If you do not already have these classes, you +can use the following while upgrading:: + + // app/View/Helper/AppHelper.php + App::uses('Helper', 'View'); + class AppHelper extends Helper { + } + + // app/Model/AppModel.php + App::uses('Model', 'Model'); + class AppModel extends Model { + } + + // app/Controller/AppController.php + App::uses('Controller', 'Controller'); + class AppController extends Controller { + } + + // app/Console/Command/AppShell.php + App::uses('Shell', 'Console'); + class AppShell extends Shell { + } + +If your application already has these files/classes you don't need to do +anything. +Additionally if you were using the core PagesController, you would need to copy +this to your app/Controller directory as well. + +.htaccess files +=============== + +The default ``.htaccess`` files have changed, you should remember to update them +or update your webservers URL re-writing scheme to match the changes done in +``.htaccess`` + + +Models +====== + +- The ``beforeDelete`` callback will be fired before behaviors beforeDelete callbacks. + This makes it consistent with the rest of the events triggered in the model layer. +- ``Model::find('threaded')`` now accepts ``$options['parent']`` if using other field + then ``parent_id``. Also if the model has TreeBehavior attached and set up with other + parent field, the threaded find will by default use that. +- Parameters for queries using prepared statements will now be part of the SQL + dump. +- Validation arrays can now be more specific with when a field is required. + The ``required`` key now accepts ``create`` and ``update``. These values will + make a field required when creating or updating. +- Model now has a ``schemaName`` property. If your application switches + datasources by modifying :php:attr:`Model::$useDbConfig` you should also + modify ``schemaName`` or use :php:meth:`Model::setDataSource()` method which + handles this for you. + +CakeSession +----------- + +.. versionchanged:: 2.1.1 + CakeSession no longer sets the P3P header, as this is the responsibility of your application. + More info see ticket `#2515 `_ in lighthouse + +Behaviors +========= + +TranslateBehavior +----------------- + +- :php:class:`I18nModel` has been moved into a separate file. + +Exceptions +========== + +The default exception rendering now includes more detailed stack traces +including file excerpts and argument dumps for all functions in the stack. + + +Utility +======= + +Debugger +-------- + +- :php:func:`Debugger::getType()` has been added. It can be used to get the type of + variables. +- :php:func:`Debugger::exportVar()` has been modified to create more readable + and useful output. + +debug() +------- + +`debug()` now uses :php:class:`Debugger` internally. This makes it consistent +with Debugger, and takes advantage of improvements made there. + +Set +--- + +- :php:func:`Set::nest()` has been added. It takes in a flat array and returns a nested array + +File +---- + +- :php:meth:`File::info()` includes filesize & mimetype information. +- :php:meth:`File::mime()` was added. + +Cache +----- + +- :php:class:`CacheEngine` has been moved into a separate file. + +Configure +--------- + +- :php:class:`ConfigReaderInterface` has been moved into a separate file. + +App +--- + +- :php:meth:`App::build()` now has the ability to register new packages using + ``App::REGISTER``. See :ref:`app-build-register` for more information. +- Classes that could not be found on configured paths will be searched inside + ``APP`` as a fallback path. This makes autoloading nested directories in + ``app/Vendor`` easier. + +Console +======= + +Test Shell +---------- + +A new TestShell has been added. It reduces the typing required to run unit +tests, and offers a file path based UI:: + + ./Console/cake test app Model/Post + ./Console/cake test app Controller/PostsController + ./Console/cake test Plugin View/Helper/MyHelper + +The old testsuite shell and its syntax are still available. + +General +------- + +- Generated files no longer contain timestamps with the generation datetime. + +Routing +======= + +Router +------ + +- Routes can now use a special ``/**`` syntax to include all trailing arguments + as a single passed argument. See the section on :ref:`connecting-routes` for + more information. +- :php:meth:`Router::resourceMap()` was added. +- :php:meth:`Router::defaultRouteClass()` was added. This method allows you to + set the default route class used for all future routes that are connected. + +Network +======= + +CakeRequest +----------- + +- Added ``is('requested')`` and ``isRequested()`` for detecting requestAction. + +CakeResponse +------------ + +- Added :php:meth:`CakeResponse::cookie()` for setting cookies. +- Added a number of methods for :ref:`cake-response-caching` + +Controller +========== + +Controller +---------- + +- :php:attr:`Controller::$uses` was modified the default value is now ``true`` + instead of false. Additionally different values are handled slightly + differently, but will behave the same in most cases. + + - ``true`` Will load the default model and merge with AppController. + - An array will load those models and merge with AppController. + - An empty array will not load any models other than those declared in the + base class. + - ``false`` will not load any models, and will not merge with the base class + either. + + +Components +========== + +AuthComponent +------------- + +- :php:meth:`AuthComponent::allow()` no longer accepts ``allow('*')`` as a wildcard + for all actions. Just use ``allow()``. This unifies the API between allow() + and deny(). +- ``recursive`` option was added to all authentication adapters. Allows you to + more easily control the associations stored in the session. + + +AclComponent +------------ + +- :php:class:`AclComponent` no longer lowercases and inflects the class name used for + ``Acl.classname``. Instead it uses the provided value as is. +- Acl backend implementations should now be put in ``Controller/Component/Acl``. +- Acl implementations should be moved into the Component/Acl directory from + Component. For example if your Acl class was called ``CustomAclComponent``, + and was in ``Controller/Component/CustomAclComponent.php``. + It should be moved into ``Controller/Component/Acl/CustomAcl.php``, and be + named ``CustomAcl``. +- :php:class:`DbAcl` has been moved into a separate file. +- :php:class:`IniAcl` has been moved into a separate file. +- :php:class:`AclInterface` has been moved into a separate file. + +Helpers +======= + +TextHelper +---------- + +- :php:meth:`TextHelper::autoLink()`, :php:meth:`TextHelper::autoLinkUrls()`, + :php:meth:`TextHelper::autoLinkEmails()` now HTML escape their input by + default. You can control this with the ``escape`` option. + +HtmlHelper +---------- + +- :php:meth:`HtmlHelper::script()` had a ``block`` option added. +- :php:meth:`HtmlHelper::scriptBlock()` had a ``block`` option added. +- :php:meth:`HtmlHelper::css()` had a ``block`` option added. +- :php:meth:`HtmlHelper::meta()` had a ``block`` option added. +- The ``$startText`` parameter of :php:meth:`HtmlHelper::getCrumbs()` can now be + an array. This gives more control and flexibility over the first crumb link. +- :php:meth:`HtmlHelper::docType()` now defaults to HTML5. +- :php:meth:`HtmlHelper::image()` now has a ``fullBase`` option. +- :php:meth:`HtmlHelper::media()` has been added. You can use this method to + create HTML5 audio/video elements. +- :term:`plugin syntax` support has been added for + :php:meth:`HtmlHelper::script()`, :php:meth:`HtmlHelper::css()`, :php:meth:`HtmlHelper::image()`. + You can now easily link to plugin assets using ``Plugin.asset``. +- :php:meth:`HtmlHelper::getCrumbList()` had the ``$startText`` parameter added. + + +View +==== + +- :php:attr:`View::$output` is deprecated. +- ``$content_for_layout`` is deprecated. Use ``$this->fetch('content');`` + instead. +- ``$scripts_for_layout`` is deprecated. Use the following instead:: + + echo $this->fetch('meta'); + echo $this->fetch('css'); + echo $this->fetch('script'); + + ``$scripts_for_layout`` is still available, but the :ref:`view blocks ` API + gives a more extensible & flexible replacement. +- The ``Plugin.view`` syntax is now available everywhere. You can use this + syntax anywhere you reference the name of a view, layout or element. +- The ``$options['plugin']`` option for :php:meth:`~View::element()` is + deprecated. You should use ``Plugin.element_name`` instead. + +Content type views +------------------ + +Two new view classes have been added to CakePHP. A new :php:class:`JsonView` +and :php:class:`XmlView` allow you to easily generate XML and JSON views. You +can learn more about these classes in the section on +:doc:`/views/json-and-xml-views` + +Extending views +--------------- + +:php:class:`View` has a new method allowing you to wrap or 'extend' a +view/element/layout with another file. See the section on +:ref:`extending-views` for more information on this feature. + +Themes +------ + +The ``ThemeView`` class is deprecated in favor of the ``View`` class. Simply +setting ``$this->theme = 'MyTheme'`` will enable theme support, and all custom +View classes which extend from ``ThemeView`` should extend ``View``. + +View blocks +----------- + +View blocks are a flexible way to create slots or blocks in your views. Blocks +replace ``$scripts_for_layout`` with a more robust and flexible API. See the +section on :ref:`view-blocks` for more information. + + +Helpers +======= + +New callbacks +------------- + +Two new callbacks have been added to Helpers. +:php:meth:`Helper::beforeRenderFile()` and :php:meth:`Helper::afterRenderFile()` +these new callbacks are fired before/after every view fragment is rendered. +This includes elements, layouts and views. + +CacheHelper +----------- + +- ```` tags now work inside elements correctly. + +FormHelper +---------- + +- FormHelper now omits disabled fields from the secured fields hash. This makes + working with :php:class:`SecurityComponent` and disabled inputs easier. +- The ``between`` option when used in conjunction with radio inputs, now behaves + differently. The ``between`` value is now placed between the legend and first + input elements. +- The ``hiddenField`` option with checkbox inputs can now be set to a specific + value such as 'N' rather than just 0. +- The ``for`` attribute for date + time inputs now reflects the first generated + input. This may result in the for attribute changing for generated datetime + inputs. +- The ``type`` attribute for :php:meth:`FormHelper::button()` can be removed now. It still + defaults to 'submit'. +- :php:meth:`FormHelper::radio()` now allows you to disable all options. + You can do this by setting either ``'disabled' => true`` or ``'disabled' => 'disabled'`` + in the ``$attributes`` array. + +PaginatorHelper +--------------- + +- :php:meth:`PaginatorHelper::numbers()` now has a ``currentClass`` option. + + +Testing +======= + +- Web test runner now displays the PHPUnit version number. +- Web test runner now defaults to displaying app tests. +- Fixtures can be created in different datasources other than $test. +- Models loaded using the ClassRegistry and using another datasource will get + their datasource name prepended with ``test_`` (e.g datasource `master` will + try to use `test_master` in the testsuite) +- Test cases are generated with class specific setup methods. + +Events +====== + +- A new generic events system has been built and it replaced the way callbacks + were dispatched. This should not represent any change to your code. +- You can dispatch your own events and attach callbacks to them at will, useful + for inter-plugin communication and easier decoupling of your classes. diff --git a/sr/appendices/2-2-migration-guide.rst b/sr/appendices/2-2-migration-guide.rst new file mode 100644 index 0000000000..441eb6cfe9 --- /dev/null +++ b/sr/appendices/2-2-migration-guide.rst @@ -0,0 +1,327 @@ +2.2 Migration Guide +################### + +CakePHP 2.2 is a fully API compatible upgrade from 2.0/2.1. This page outlines the +changes and improvements made for 2.2. + +.. _required-steps-to-upgrade-2-2: + +Required steps to upgrade +========================= + +When upgrading to CakePHP 2.2 its important to add a few new configuration +values to ``app/Config/bootstrap.php``. Adding these will ensure consistent +behavior with 2.1.x:: + + // Enable the Dispatcher filters for plugin assets, and + // CacheHelper. + Configure::write('Dispatcher.filters', array( + 'AssetDispatcher', + 'CacheDispatcher' + )); + + // Add logging configuration. + CakeLog::config('debug', array( + 'engine' => 'FileLog', + 'types' => array('notice', 'info', 'debug'), + 'file' => 'debug', + )); + CakeLog::config('error', array( + 'engine' => 'FileLog', + 'types' => array('warning', 'error', 'critical', 'alert', 'emergency'), + 'file' => 'error', + )); + +You will also need to modify ``app/Config/core.php``. Change the value of +:php:const:`LOG_ERROR` to :php:const:`LOG_ERR`:: + + define('LOG_ERROR', LOG_ERR); + +When using ``Model::validateAssociated()`` or ``Model::saveAssociated()`` and +primary model validation fails, the validation errors of associated models are no longer wiped out. +``Model::$validationErrors`` will now always show all the errors. +You might need to update your test cases to reflect this change. + +Console +======= + +I18N extract shell +------------------ + +- An option was added to overwrite existing POT files by default:: + + ./Console/cake i18n extract --overwrite + + +Models +====== + +- ``Model::find('count')`` will now call the custom find methods with + ``$state = 'before'`` and ``$queryData['operation'] = 'count'``. + In many cases custom finds already return correct counts for pagination, + but ``'operation'`` key allows more flexibility to build other queries, + or drop joins which are required for the custom finder itself. + As the pagination of custom find methods never worked quite well it required + workarounds for this in the model level, which are now no longer needed. +- ``Model::find('first')`` will now return an empty array when no records are found. + +Datasources +=========== + +- Dbo datasources now supports real nested transactions. If you need to use this + feature in your application, enable it using + ``ConnectionManager::getDataSource('default')->useNestedTransactions = true;`` + +Testing +======= + +- The webrunner now includes links to re-run a test with debug output. +- Generated test cases for Controller now subclass + :php:class:`ControllerTestCase`. + + +Error Handling +============== + +- When repeat exceptions, or exception are raised when rendering error pages, + the new ``error`` layout will be used. It's recommended to not use additional + helpers in this layout as its intended for development level errors only. This + fixes issues with fatal errors in rendering error pages due to helper usage in + the ``default`` layout. +- It is important to copy the ``app/View/Layouts/error.ctp`` into your app + directory. Failing to do so will make error page rendering fail. +- You can now configure application specific console error handling. By setting + ``Error.consoleHandler``, and ``Exception.consoleHandler`` you can define the + callback that will handle errors/exceptions raised in console applications. +- The handler configured in ``Error.handler`` and ``Error.consoleHandler`` will + receive fatal error codes (ie. ``E_ERROR``, ``E_PARSE``, ``E_USER_ERROR``). + +Exceptions +---------- + +- The :php:class:`NotImplementedException` was added. + + +Core +==== + +Configure +--------- + +- :php:meth:`Configure::dump()` was added. It is used to persist configuration + data in durable storage like files. Both :php:class:`PhpReader` and + :php:class:`IniReader` work with it. +- A new config parameter 'Config.timezone' is available in which you can set + users' timezone string. eg. You can do ``Configure::write('Config.timezone', + 'Europe/Paris')``. If a method of ``CakeTime`` class is called with + ``$timezone`` parameter as null and 'Config.timezone' is set, then the value + of 'Config.timezone' will be used. This feature allows you to set users' + timezone just once instead of passing it each time in function calls. + + +Controller +========== + +AuthComponent +------------- + +- The options for adapters defined in :php:attr:`AuthComponent::$authenticate` + now accepts a ``contain`` option. This is used to set containable options for + when user records are loaded. + +CookieComponent +--------------- + +- You can now encrypt cookie values with the rijndael cipher. This requires + the `mcrypt `_ extension to be installed. Using + rijndael gives cookie values actual encryption, and is recommended in place of + the XOR cipher available in previous releases. The XOR cipher is still the + default cipher scheme to maintain compatibility with previous releases. You + can read more in the :php:meth:`Security::rijndael()` documentation. + +Pagination +========== + +- Paginating custom finders will now return correct counts, see Model changes + for more info. + + +Network +======= + +CakeEmail +--------- + +- :php:meth:`CakeEmail::charset()` and :php:meth:`CakeEmail::headerCharset()` + were added. +- Legacy Japanese encodings are now handled correctly. ``ISO-2202-JP`` is used + when the encoding is ``ISO-2202-JP-MS`` which works around a number of issues + in mail clients when dealing with the CP932 and Shift_JIS encodings. +- :php:meth:`CakeEmail::theme()` was added. +- :php:meth:`CakeEmail::domain()` was added. You can use this method to set the + domain name used when sending email from a CLI script or if you want to + control the hostname used to send email. +- You can now define ``theme`` and ``helpers`` in your EmailConfig class. + +CakeRequest +----------- + +- CakeRequest will now automatically decode + ``application/x-www-form-urlencoded`` request bodies on ``PUT`` and ``DELETE`` + requests. This data will be available as ``$this->data`` just like POST data + is. + +Utility +======= + +Set +--- + +- The :php:class:`Set` class is now deprecated, and replaced by the :php:class:`Hash` class. + Set will not be removed until 3.0. +- :php:meth:`Set::expand()` was added. + +Hash +---- + +The :php:class:`Hash` class was added in 2.2. It replaced Set providing a more +consistent, reliable and performant API to doing many of the same tasks Set +does. See the :doc:`/core-utility-libraries/hash` page for more detail. + +CakeTime +-------- + +- The ``$userOffset`` parameter has been replaced with ``$timezone`` parameter + in all relevant functions. So instead of numeric offset you can now pass in a + timezone string or DateTimeZone object. Passing numeric offsets for + ``$timezone`` parameter is still possible for backwards compatibility. +- :php:meth:`CakeTime::timeAgoInWords()` had the ``accuracy`` option added. + This option allows you to specify how accurate formatted times should be. + +- New methods added: + + * :php:meth:`CakeTime::toServer()` + * :php:meth:`CakeTime::timezone()` + * :php:meth:`CakeTime::listTimezones()` + +- The ``$dateString`` parameter in all methods now accepts a DateTime object. + + +Helpers +======= + +FormHelper +---------- + +- FormHelper now better handles adding required classes to inputs. It now + honors the ``on`` key. +- :php:meth:`FormHelper::radio()` now supports an ``empty`` which works similar + to the empty option on ``select()``. +- Added :php:meth:`FormHelper::inputDefaults()` to set common properties for + each of the inputs generated by the helper + +TimeHelper +---------- + +- Since 2.1, TimeHelper uses the CakeTime class for all its relevant methods. + The ``$userOffset`` parameter has been replaced with ``$timezone`` parameter. +- :php:meth:`TimeHelper::timeAgoInWords()` has the ``element`` option added. + This allows you to specify an HTML element to wrap the formatted time. + +HtmlHelper +---------- + +- :php:meth:`HtmlHelper::tableHeaders()` now supports setting attributes per + table cell. + + +Routing +======= + +Dispatcher +---------- + +- Event listeners can now be attached to the dispatcher calls, those will have + the ability to change the request information or the response before it is + sent to the client. Check the full documentation for this new features in + :doc:`/development/dispatch-filters` +- With the addition of :doc:`/development/dispatch-filters` you'll need to + update ``app/Config/bootstrap.php``. See + :ref:`required-steps-to-upgrade-2-2`. + +Router +------ + +- :php:meth:`Router::setExtensions()` has been added. With the new method you can + now add more extensions to be parsed, for example within a plugin routes file. + +Cache +===== + +Redis Engine +------------ + +A new caching engine was added using the `phpredis extension +`_ it is configured similarly to the +Memcache engine. + +Cache groups +------------ + +It is now possible to tag or label cache keys under groups. This makes it +simpler to mass-delete cache entries associated to the same label. Groups are +declared at configuration time when creating the cache engine:: + + Cache::config(array( + 'engine' => 'Redis', + ... + 'groups' => array('post', 'comment', 'user') + )); + +You can have as many groups as you like, but keep in mind they cannot be +dynamically modified. + +The :php:meth:`Cache::clearGroup()` class method was added. It takes the group +name and deletes all entries labeled with the same string. + +Log +=== + +Changes in :php:class:`CakeLog` now require, some additional configuration in +your ``app/Config/bootstrap.php``. See :ref:`required-steps-to-upgrade-2-2`, +and :doc:`/core-libraries/logging`. + +- The :php:class:`CakeLog` class now accepts the same log levels as defined in + `RFC 5424 `_. Several convenience + methods have also been added: + + * :php:meth:`CakeLog::emergency($message, $scope = array())` + * :php:meth:`CakeLog::alert($message, $scope = array())` + * :php:meth:`CakeLog::critical($message, $scope = array())` + * :php:meth:`CakeLog::error($message, $scope = array())` + * :php:meth:`CakeLog::warning($message, $scope = array())` + * :php:meth:`CakeLog::notice($message, $scope = array())` + * :php:meth:`CakeLog::info($message, $scope = array())` + * :php:meth:`CakeLog::debug($message, $scope = array())` + +- A third argument ``$scope`` has been added to :php:meth:`CakeLog::write`. + See :ref:`logging-scopes`. +- A new log engine: :php:class:`ConsoleLog` has been added. + +Model Validation +================ + +- A new object ``ModelValidator`` was added to delegate the work of validating + model data, it should be transparent to the application and fully backwards + compatible. It also exposes a rich API to add, modify and remove validation + rules. Check docs for this object in :doc:`/models/data-validation`. + +- Custom validation functions in your models need to have "public" visibility + so that they are accessible by ``ModelValidator``. + +- New validation rules added: + + * :php:meth:`Validation::naturalNumber()` + * :php:meth:`Validation::mimeType()` + * :php:meth:`Validation::uploadError()` + diff --git a/sr/appendices/2-3-migration-guide.rst b/sr/appendices/2-3-migration-guide.rst new file mode 100644 index 0000000000..2c47db0d9c --- /dev/null +++ b/sr/appendices/2-3-migration-guide.rst @@ -0,0 +1,326 @@ +2.3 Migration Guide +################### + +CakePHP 2.3 is a fully API compatible upgrade from 2.2. This page outlines +the changes and improvements made in 2.3. + +Constants +========= + +An application can now easily define :php:const:`CACHE` and :php:const:`LOGS`, +as they are conditionally defined by CakePHP now. + +Caching +======= + +- FileEngine is always the default cache engine. In the past a number of people + had difficulty setting up and deploying APC correctly both in cli + web. + Using files should make setting up CakePHP simpler for new developers. + +- `Configure::write('Cache.viewPrefix', 'YOURPREFIX');` has been added to `core.php` + to allow multiple domains/languages per setup. + +Component +========= + +AuthComponent +------------- +- A new property ``AuthComponent::$unauthorizedRedirect`` has been added. + + - For default ``true`` value user is redirected to referrer URL upon authorization failure. + - If set to a string or array user is redirected to that URL. + - If set to false a ForbiddenException exception is thrown instead of redirecting. + +- A new authenticate adapter has been added to support blowfish/bcrypt hashed + passwords. You can now use ``Blowfish`` in your ``$authenticate`` array to + allow bcrypt passwords to be used. + +- :php:meth:`AuthComponent::redirect()` has been deprecated. + Use :php:meth:`AuthComponent::redirectUrl()` instead. + +PaginatorComponent +------------------ + +- PaginatorComponent now supports the ``findType`` option. This can be used to + specify what find method you want used for pagination. This is a bit easier + to manage and set than the 0'th index. + +- PaginatorComponent now throws a `NotFoundException` when trying to access a page + which is out of range (i.e. requested page is greater than total page count). + +SecurityComponent +----------------- + +- SecurityComponent now supports the ``unlockedActions`` option. This can be used to + disable all security checks for any actions listed in this option. + +RequestHandlerComponent +----------------------- + +- :php:meth:`RequestHandlerComponent::viewClassMap()` has been added, which is used to map a type + to view class name. You can add ``$settings['viewClassMap']`` for automatically setting + the correct viewClass based on extension/content type. + +CookieComponent +--------------- + +- :php:meth:`CookieComponent::check()` was added. This method works the same as + :php:meth:`CakeSession::check()` does. + +Console +======= + +- The ``server`` shell was added. You can use this to start the PHP5.4 + webserver for your CakePHP application. +- Baking a new project now sets the application's cache prefix to the name of + the application. + +I18n +==== + +L10n +---- + +- ``nld`` is now the default locale for Dutch as specified by ISO 639-3 and ``dut`` its alias. + The locale folders have to be adjusted accordingly (from `/Locale/dut/` to `/Locale/nld/`). +- Albanian is now ``sqi``, Basque is now ``eus``, Chinese is now ``zho``, Tibetan is now ``bod``, + Czech is now ``ces``, Farsi is now ``fas``, French is now ``fra``, Icelandic is now ``isl``, + Macedonian is now ``mkd``, Malaysian is now ``msa``, Romanian is now ``ron``, Serbian is now ``srp`` + and Slovak is now ``slk``. The corresponding locale folders have to be adjusted, as well. + +Core +==== + +CakePlugin +---------- + +- :php:meth:`CakePlugin::load()` can now take a new ``ignoreMissing`` option. Setting it to true will + prevent file include errors when you try to load routes or bootstrap but they don't exist for a plugin. + So essentially you can now use the following statement which will load all plugins and their routes and + bootstrap for whatever plugin it can find:: + ``CakePlugin::loadAll(array(array('routes' => true, 'bootstrap' => true, 'ignoreMissing' => true)))`` + + +Configure +--------- + +- :php:meth:`Configure::check()` was added. This method works the same as + :php:meth:`CakeSession::check()` does. + +- :php:meth:`ConfigReaderInterface::dump()` was added. Please ensure any custom readers you have now + implement a ``dump()`` method. + +- The ``$key`` parameter of :php:meth:`IniReader::dump()` now supports keys like `PluginName.keyname` + similar to ``PhpReader::dump()``. + +Error +===== + +Exceptions +---------- + +- CakeBaseException was added, which all core Exceptions now extend. The base exception + class also introduces the ``responseHeader()`` method which can be called on created Exception instances + to add headers for the response, as Exceptions don't reuse any response instance. + +Model +===== + +- Support for the biginteger type was added to all core datasources, and + fixtures. +- Support for ``FULLTEXT`` indexes was added for the MySQL driver. + + +Models +------ + +- ``Model::find('list')`` now sets the ``recursive`` based on the max + containment depth or recursive value. When list is used with + ContainableBehavior. +- ``Model::find('first')`` will now return an empty array when no records are found. + +Validation +---------- + +- Missing validation methods will **always** trigger errors now instead of + only in development mode. + +Network +======= + +SmtpTransport +------------- + +- TLS/SSL support was added for SMTP connections. + +CakeRequest +----------- + +- :php:meth:`CakeRequest::onlyAllow()` was added. +- :php:meth:`CakeRequest::query()` was added. + +CakeResponse +------------ + +- :php:meth:`CakeResponse::file()` was added. +- The content types `application/javascript`, `application/xml`, + `application/rss+xml` now also send the application charset. + +CakeEmail +--------- + +- The ``contentDisposition`` option was added to + :php:meth:`CakeEmail::attachments()`. This allows you to disable the + Content-Disposition header added to attached files. + +HttpSocket +---------- + +- :php:class:`HttpSocket` now verifies SSL certificates by default. If you are + using self-signed certificates or connecting through proxies you may need to + use some of the new options to augment this behavior. See + :ref:`http-socket-ssl-options` for more information. +- ``HttpResponse`` was renamed to ``HttpSocketResponse``. This + avoids a common issue with the HTTP PECL extension. There is an + ``HttpResponse`` class provided as well for compatibility reasons. + +Routing +======= + +Router +------ + +- Support for ``tel:``, ``sms:`` were added to :php:meth:`Router::url()`. + +View +==== + +- MediaView is deprecated, and you can use new features in + :php:class:`CakeResponse` to achieve the same results. +- Serialization in Json and Xml views has been moved to ``_serialize()`` +- beforeRender and afterRender callbacks are now being called in Json and Xml + views when using view templates. +- :php:meth:`View::fetch()` now has a ``$default`` argument. This argument can + be used to provide a default value should a block be empty. +- :php:meth:`View::prepend()` has been added to allow prepending content to + existing block. +- :php:class:`XmlView` now uses the ``_rootNode`` view variable to customize the + top level XML node. +- :php:meth:`View::elementExists()` was added. You can use this method to check + if elements exist before using them. +- :php:meth:`View::element()` had the ``ignoreMissing`` option added. You can + use this to suppress the errors triggered by missing view elements. +- :php:meth:`View::startIfEmpty()` was added. + +Layout +------ + +- The doctype for layout files in the app folder and the bake templates in the + cake package has been changed from XHTML to HTML5. + +Helpers +======= + +- New property ``Helper::$settings`` has been added for your helper setting. The + ``$settings`` parameter of ``Helper::__construct()`` is merged with + ``Helper::$settings``. + +FormHelper +---------- + +- :php:meth:`FormHelper::select()` now accepts a list of values in the disabled + attribute. Combined with ``'multiple' => 'checkbox'``, this allows you to + provide a list of values you want disabled. +- :php:meth:`FormHelper::postLink()` now accepts a ``method`` key. This allows + you to create link forms using HTTP methods other than POST. +- When creating inputs with :php:meth:`FormHelper::input()` you can now set the + ``errorMessage`` option to false. This will disable the error message display, + but leave the error class names intact. +- The FormHelper now also adds the HTML5 ``required`` attribute to your input + elements based on validation rules for a field. If you have a "Cancel" button + in your form which submits the form then you should add ``'formnovalidate' => true`` + to your button options to prevent the triggering of validation in HTML. You + can also prevent the validation triggering for the whole form by adding + ``'novalidate' => true`` in your FormHelper::create() options. +- :php:meth:`FormHelper::input()` now generates input elements of type ``tel`` + and ``email`` based on field names if ``type`` option is not specified. + +HtmlHelper +---------- + +- :php:meth:`HtmlHelper::getCrumbList()` now has the ``separator``, + ``firstClass`` and ``lastClass`` options. These allow you to better control + the HTML this method generates. + +TextHelper +---------- + +- :php:meth:`TextHelper::tail()` was added to truncate text starting from the end. +- `ending` in :php:meth:`TextHelper::truncate()` is deprecated in favor of `ellipsis` + +PaginatorHelper +--------------- + +- :php:meth:`PaginatorHelper::numbers()` now has a new option ``currentTag`` to + allow specifying extra tag for wrapping current page number. +- For methods: :php:meth:`PaginatorHelper::prev()` and :php:meth:`PaginatorHelper::next()` it + is now possible to set the ``tag`` option to ``false`` to disable the wrapper. + Also a new option `disabledTag` has been added for these two methods. + + +Testing +======= + +- A core fixture for the default ``cake_sessions`` table was added. You can use + it by adding ``core.cake_sessions`` to your fixture list. +- :php:meth:`CakeTestCase::getMockForModel()` was added. This simplifies getting + mock objects for models. + +Utility +======= + +CakeNumber +---------- + +- :php:meth:`CakeNumber::fromReadableSize()` was added. +- :php:meth:`CakeNumber::formatDelta()` was added. +- :php:meth:`CakeNumber::defaultCurrency()` was added. + +Folder +------ + +- :php:meth:`Folder::copy()` and :php:meth:`Folder::move()` now support the + ability to merge the target and source directories in addition to + skip/overwrite. + + +String +------ + +- :php:meth:`String::tail()` was added to truncate text starting from the end. +- `ending` in :php:meth:`String::truncate()` is deprecated in favor of `ellipsis` + +Debugger +-------- + +- :php:meth:`Debugger::exportVar()` now outputs private and protected properties + in PHP >= 5.3.0. + +Security +-------- + +- Support for `bcrypt `_ + was added. See the :php:class:`Security::hash()` documentation for more + information on how to use bcrypt. + +Validation +---------- + +- :php:meth:`Validation::fileSize()` was added. + +ObjectCollection +---------------- + +- :php:meth:`ObjectCollection::attached()` was deprecated in favor of the new + method :php:meth:`ObjectCollection::loaded()`. This unifies the access to the + ObjectCollection as load()/unload() already replaced attach()/detach(). diff --git a/sr/appendices/2-4-migration-guide.rst b/sr/appendices/2-4-migration-guide.rst new file mode 100644 index 0000000000..73094f212a --- /dev/null +++ b/sr/appendices/2-4-migration-guide.rst @@ -0,0 +1,294 @@ +2.4 Migration Guide +################### + +CakePHP 2.4 is a fully API compatible upgrade from 2.3. This page outlines +the changes and improvements made in 2.4. + +Console +======= + +- Logged notice messages will now be colourized in terminals that support + colours. +- ConsoleShell is now deprecated. + +SchemaShell +----------- + +- ``cake schema generate`` now supports the ``--exclude`` parameter. +- The constant ``CAKEPHP_SHELL`` is now deprecated and will be removed in CakePHP 3.0. + +BakeShell +--------- + +- ``cake bake model`` now supports baking ``$behaviors``. Finding `lft`, `rght` and `parent_id` fields + in your table it will add the Tree behavior, for example. You can also extend the ModelTask to support your own + behaviors to be recognized. +- ``cake bake`` for views, models, controllers, tests and fixtures now supports a ``-f`` or ``--force`` parameter to + force overwriting of files. +- Tasks in core can now be aliased in the same way you would Helpers, Components and Behaviors + +FixtureTask +----------- + +- ``cake bake fixture`` now supports a ``--schema`` parameter to allow baking all fixtures with noninteractive "all" + while using schema import. + +Core +==== + +Constants +--------- + +- Constants ``IMAGES_URL``, ``JS_URL``, ``CSS_URL`` have been deprecated and + replaced with config variables ``App.imageBaseUrl``, ``App.jsBaseUrl``, + ``App.cssBaseUrl`` respectively. + +- Constants ``IMAGES``, ``JS``, ``CSS`` have been deprecated. + +Object +------ + +- :php:meth:`Object::log()` had the ``$scope`` parameter added. + + +Components +========== + +AuthComponent +------------- +- AuthComponent now supports proper stateless mode when using 'Basic' or 'Digest' + authenticators. Starting of session can be prevented by setting :php:attr:`AuthComponent::$sessionKey` + to false. Also now when using only 'Basic' or 'Digest' you are no longer + redirected to login page. For more info check the :php:class:`AuthComponent` page. +- Property :php:attr:`AuthComponent::$authError` can be set to boolean ``false`` to suppress flash message from being displayed. + +PasswordHasher +-------------- +- Authenticating objects now use new password hasher objects for password hash + generation and checking. See :ref:`hashing-passwords` for more info. + +DbAcl +----- + +- DbAcl now uses ``INNER`` joins instead of ``LEFT`` joins. This improves + performance for some database vendors. + +Model +===== + +Models +------ + +- :php:meth:`Model::save()`, :php:meth:`Model::saveField()`, :php:meth:`Model::saveAll()`, + :php:meth:`Model::saveAssociated()`, :php:meth:`Model::saveMany()` + now take a new ``counterCache`` option. You can set it to false to avoid + updating counter cache values for the particular save operation. +- :php:meth:`Model::clear()` was added. + +Datasource +---------- + +- Mysql, Postgres, and SQLserver now support a 'settings' array in the + connection definition. This key => value pair will be issued as ``SET`` commands when the + connection is created. +- Mysql driver now supports SSL options. + + +View +==== + +JsonView +-------- + +- JSONP support has been added to :php:class:`JsonView`. +- The ``_serialize`` key now supports renaming serialized variables. +- When debug > 0 JSON will be pretty printed. + +XmlView +------- + +- The ``_serialize`` key now supports renaming serialized variables. +- When debug > 0 XML will be pretty printed. + +HtmlHelper +---------- + +- The API for :php:meth:`HtmlHelper::css()` has been been simplified. You can + now provide an array of options as the second argument. When you do, the + ``rel`` attribute defaults to 'stylesheet'. +- New option ``escapeTitle`` added to :php:meth:`HtmlHelper::link()` to control + escaping of only link title and not attributes. + +TextHelper +---------- + +- :php:meth:`TextHelper::autoParagraph()` has been added. It allows to + automatically convert text into HTML paragraphs. + +PaginatorHelper +--------------- + +- :php:meth:`PaginatorHelper::param()` has been added. +- The first page no longer contains ``/page:1`` or ``?page=1`` in the URL. This helps prevent + duplicate content issues where you would need to use canonical or noindex otherwise. + +FormHelper +---------- + +- The ``round`` option was added to :php:meth:`FormHelper::dateTime()`. Can be set to ``up`` or ``down`` + to force rounding in either direction. Defaults to null which rounds half up according to ``interval``. + +Network +======= + +CakeRequest +----------- + +- :php:meth:`CakeRequest::param()` has been added. +- :php:meth:`CakeRequest::is()` has been modified to support an array of types and will return true if the request matches any type. +- :php:meth:`CakeRequest::isAll()` has been added to check that a request matches all the given types. + +CakeResponse +------------ + +- :php:meth:`CakeResponse::location()` has been added to get or set the redirect location header. + +CakeEmail +--------- + +- Logged email messages now have the scope of ``email`` by default. If you are + not seeing email contents in your logs, be sure to add the ``email`` scope to + your logging configuration. +- :php:meth:`CakeEmail::emailPattern()` was added. This method can be used to + relax email validation rules. This is useful when dealing with certain + Japanese hosts that allow non-compliant addresses to be used. +- :php:meth:`CakeEmail::attachments()` now allows you to provide the file + contents directly using the ``data`` key. +- Configuration data is now correctly merged with transport classes. + +HttpSocket +---------- + +- :php:meth:`HttpSocket::patch()` has been added. + + +I18n +==== + +L10n +---- + +- ``ell`` is now the default locale for Greek as specified by ISO 639-3 and ``gre`` its alias. + The locale folders have to be adjusted accordingly (from `/Locale/gre/` to `/Locale/ell/`). +- ``fas`` is now the default locale for Farsi as specified by ISO 639-3 and ``per`` its alias. + The locale folders have to be adjusted accordingly (from `/Locale/per/` to `/Locale/fas/`). +- ``sme`` is now the default locale for Sami as specified by ISO 639-3 and ``smi`` its alias. + The locale folders have to be adjusted accordingly (from `/Locale/smi/` to `/Locale/sme/`). +- ``mkd`` replaces ``mk`` as default locale for Macedonian as specified by ISO 639-3. + The corresponding locale folders have to be adjusted, as well. +- Catalog code ``in`` has been dropped in favor of ``id`` (Indonesian), + ``e`` has been dropped in favor of ``el`` (Greek), + ``n`` has been dropped in favor of ``nl`` (Dutch), + ``p`` has been dropped in favor of ``pl`` (Polish), + ``sz`` has been dropped in favor of ``se`` (Sami). +- Kazakh has been added with ``kaz`` as locale and ``kk`` as catalog code. +- Kalaallisut has been added with ``kal`` as locale and ``kl`` as catalog code. +- The constant ``DEFAULT_LANGUAGE`` has been deprecated in favor of Configure value ``Config.language``. + +Logging +======= + +- Log engines do not need the suffix ``Log`` anymore in their setup configuration. So for the + FileLog engine it suffices to define ``'engine' => 'File'`` now. This unifies the way engines + are named in configuration (see Cache engines for example). + Note: If you have a Log engine like ``DatabaseLogger`` that does not follow the convention to + use a suffix ``Log`` for your class name you have to adjust your class name to ``DatabaseLog``. + You should also avoid class names like ``SomeLogLog`` which include the suffix twice at the end. + +FileLog +------- + +- Two new config options ``size`` and ``rotate`` have been added for :ref:`FileLog ` engine. +- In debug mode missing directories will now be automatically created to avoid unnecessary errors thrown. + +SyslogLog +--------- + +- The new logging engine :ref:`SyslogLog ` was added to stream messages to syslog. + +Cache +===== + +FileEngine +---------- + +- In debug mode missing directories will now be automatically created to avoid unnecessary errors thrown. + +Utility +======= + +General +------- + +- :php:func:`pr()` no longer outputs HTML when running in cli mode. + +Sanitize +-------- + +- ``Sanitize`` class has been deprecated. + +Validation +---------- + +- :php:meth:`Validation::date()` now supports the ``y`` and ``ym`` formats. +- The country code of :php:meth:`Validation::phone()` for Canada has been changed from ``can`` to + ``ca`` to unify the country codes for validation methods according to ISO 3166 (two letter codes). + +CakeNumber +---------- + +- The currencies ``AUD``, ``CAD`` and ``JPY`` have been added. +- The symbols for ``GBP`` and ``EUR`` are now UTF-8. If you upgrade a non-UTF-8 application, + make sure that you update the static ``$_currencies`` attribute with the appropriate + HTML entity symbols (``£`` and ``€``) before you use those currencies. +- The ``fractionExponent`` option was added to + :php:meth:`CakeNumber::currency()`. + +CakeTime +-------- + +- :php:meth:`CakeTime::isPast()` and :php:meth:`CakeTime::isFuture()` were + added. +- :php:meth:`CakeTime::timeAgoInWords()` has two new options to customize the output strings: + ``relativeString`` (defaults to ``%s ago``) and ``absoluteString`` (defaults to ``on %s``). +- :php:meth:`CakeTime::timeAgoInWords()` uses fuzzy terms when time is below thresholds. + + +Xml +--- + +- New option ``pretty`` has been added to :php:meth:`Xml::fromArray()` to return nicely formatted Xml + + +Error +===== + +ErrorHandler +------------ + +- New configuration option ``skipLog`` has been added, to allow skipping certain + Exception types to be logged. ``Configure::write('Exception.skipLog', array('NotFoundException', 'ForbiddenException'));`` + will avoid these exceptions and the ones extending them to be be logged when + ``'Exception.log'`` config is ``true`` + +Routing +======= + +Router +------ + +- :php:meth:`Router::fullBaseUrl()` was added together with ``App.fullBaseUrl`` Configure value. They replace + :php:const:`FULL_BASE_URL` which is now deprecated. +- :php:meth:`Router::parse()` now parses query string arguments. + + diff --git a/sr/appendices/cakephp-development-process.rst b/sr/appendices/cakephp-development-process.rst new file mode 100644 index 0000000000..a2fc2f09b9 --- /dev/null +++ b/sr/appendices/cakephp-development-process.rst @@ -0,0 +1,56 @@ +CakePHP Development Process +########################### + +Here we attempt to explain the process we use when developing the +CakePHP framework. We rely heavily on community interaction through +tickets and IRC chat. IRC is the best place to find members of the +`development team `_ and discuss +ideas, the latest code, and make general comments. If something more +formal needs to be proposed or there is a problem with a release, the +ticket system is the best place to share your thoughts. + +We currently maintain 4 versions of CakePHP. + +- **stable** : Tagged releases intended for production where stability + is more important than features. Issues filed against these releases + will be fixed in the related branch, and be part of the next release. +- **maintenance branch** : Development branches become maintenance + branches once a stable release point has been reached. Maintenance + branches are where all bugfixes are committed before making their way + into a stable release. Maintenance branches have the same name as the + major version they are for example *1.2*. If you are using a stable + release and need fixes that haven't made their way into a stable + release check here. +- **development branches** : Development branches contain leading edge + fixes and features. They are named after the version number they are + for example *1.3*. Once development branches have reached a stable + release point they become maintenance branches, and no further new + features are introduced unless absolutely necessary. +- **feature branches** : Feature branches contain unfinished or + possibly unstable features and are recommended only for power users + interested in the most advanced feature set and willing to contribute + back to the community. Feature branches are named with the following + convention *version-feature*. An example would be *1.3-router* Which + would contain new features for the Router for 1.3. + +Hopefully this will help you understand what version is right for you. +Once you pick your version you may feel compelled to contribute a bug +report or make general comments on the code. + +- If you are using a stable version or maintenance branch, please submit + tickets or discuss with us on IRC. +- If you are using the development branch or feature branch, the first + place to go is IRC. If you have a comment and cannot reach us in IRC + after a day or two, please submit a ticket. + +If you find an issue, the best answer is to write a test. The best +advice we can offer in writing tests is to look at the ones included in +the core. + +As always, if you have any questions or comments, visit us at #cakephp +on irc.freenode.net. + + +.. meta:: + :title lang=en: CakePHP Development Process + :keywords lang=en: maintenance branch,community interaction,community feature,necessary feature,stable release,ticket system,advanced feature,power users,feature set,chat irc,leading edge,router,new features,members,attempt,development branches,branch development diff --git a/sr/appendices/glossary.rst b/sr/appendices/glossary.rst new file mode 100644 index 0000000000..80ff5cefc1 --- /dev/null +++ b/sr/appendices/glossary.rst @@ -0,0 +1,70 @@ +Glossary +######## + +.. glossary:: + + routing array + An array of attributes that are passed to :php:meth:`Router::url()`. + They typically look like:: + + array('controller' => 'posts', 'action' => 'view', 5) + + HTML attributes + An array of key => values that are composed into HTML attributes. For example:: + + // Given + array('class' => 'my-class', 'target' => '_blank') + + // Would generate + class="my-class" target="_blank" + + If an option can be minimized or accepts it's name as the value, then ``true`` + can be used:: + + // Given + array('checked' => true) + + // Would generate + checked="checked" + + plugin syntax + Plugin syntax refers to the dot separated class name indicating classes + are part of a plugin. E.g. ``DebugKit.Toolbar`` The plugin is DebugKit, + and the class name is Toolbar. + + dot notation + Dot notation defines an array path, by separating nested levels with ``.`` + For example:: + + Asset.filter.css + + Would point to the following value:: + + array( + 'Asset' => array( + 'filter' => array( + 'css' => 'got me' + ) + ) + ) + + CSRF + Cross Site Request Forgery. Prevents replay attacks, double + submissions and forged requests from other domains. + + routes.php + A file in APP/Config that contains routing configuration. + This file is included before each request is processed. + It should connect all the routes your application needs so + requests can be routed to the correct controller + action. + + DRY + Don't repeat yourself. Is a principle of software development aimed at + reducing repetition of information of all kinds. In CakePHP DRY is used + to allow you to code things once and re-use them across your + application. + + +.. meta:: + :title lang=en: Glossary + :keywords lang=en: html attributes,array class,array controller,glossary glossary,target blank,dot notation,routing configuration,forgery,replay,router,syntax,config,submissions diff --git a/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst b/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst new file mode 100644 index 0000000000..5c49c43bd8 --- /dev/null +++ b/sr/appendices/migrating-from-cakephp-1-2-to-1-3.rst @@ -0,0 +1,778 @@ +Migrating from CakePHP 1.2 to 1.3 +################################# + +This guide summarizes many of the changes necessary when migrating +from a 1.2 to 1.3 CakePHP core. Each section contains relevant +information for the modifications made to existing methods as well +as any methods that have been removed/renamed. + +**App File Replacements (important)** + + +- webroot/index.php: Must be replaced due to changes in + bootstrapping process. +- config/core.php: Additional settings have been put in place + which are required for PHP 5.3. +- webroot/test.php: Replace if you want to run unit tests. + +Removed Constants +~~~~~~~~~~~~~~~~~ + +The following constants have been removed from CakePHP. If your +application depends on them you must define them in +``app/config/bootstrap.php`` + + +- ``CIPHER_SEED`` - It has been replaced with Configure class var + ``Security.cipherSeed`` which should be changed in + ``app/config/core.php`` +- ``PEAR`` +- ``INFLECTIONS`` +- ``VALID_NOT_EMPTY`` +- ``VALID_EMAIL`` +- ``VALID_NUMBER`` +- ``VALID_YEAR`` + +Configuration and application bootstrapping +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Bootstrapping Additional Paths.** + +In your app/config/bootstrap.php you may have variables like +``$pluginPaths`` or ``$controllerPaths``. +There is a new way to add those paths. As of 1.3 RC1 the +``$pluginPaths`` variables will no longer work. You must use +``App::build()`` to modify paths. + +:: + + App::build(array( + 'plugins' => array( + '/full/path/to/plugins/', + '/next/full/path/to/plugins/' + ), + 'models' => array( + '/full/path/to/models/', + '/next/full/path/to/models/' + ), + 'views' => array( + '/full/path/to/views/', + '/next/full/path/to/views/' + ), + 'controllers' => array( + '/full/path/to/controllers/', + '/next/full/path/to/controllers/' + ), + 'datasources' => array( + '/full/path/to/datasources/', + '/next/full/path/to/datasources/' + ), + 'behaviors' => array( + '/full/path/to/behaviors/', + '/next/full/path/to/behaviors/' + ), + 'components' => array( + '/full/path/to/components/', + '/next/full/path/to/components/' + ), + 'helpers' => array( + '/full/path/to/helpers/', + '/next/full/path/to/helpers/' + ), + 'vendors' => array( + '/full/path/to/vendors/', + '/next/full/path/to/vendors/' + ), + 'shells' => array( + '/full/path/to/shells/', + '/next/full/path/to/shells/' + ), + 'locales' => array( + '/full/path/to/locale/', + '/next/full/path/to/locale/' + ), + 'libs' => array( + '/full/path/to/libs/', + '/next/full/path/to/libs/' + ) + )); + +Also changed is the order in which bootstrapping occurs. In the +past ``app/config/core.php`` was loaded **after** +``app/config/bootstrap.php``. This caused any ``App::import()`` in +an application bootstrap to be un-cached and considerably slower +than a cached include. In 1.3 core.php is loaded and the core cache +configs are created **before** bootstrap.php is loaded. + +**Loading custom inflections** + +``inflections.php`` has been removed, it was an unnecessary file +hit, and the related features have been refactored into a method to +increase their flexibility. You now use ``Inflector::rules()`` to +load custom inflections:: + + Inflector::rules('singular', array( + 'rules' => array( + '/^(bil)er$/i' => '\1', + '/^(inflec|contribu)tors$/i' => '\1ta' + ), + 'uninflected' => array('singulars'), + 'irregular' => array('spins' => 'spinor') + )); + +Will merge the supplied rules into the infection sets, with the +added rules taking precedence over the core rules. + +File renames and internal changes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Library Renames** + +Core libraries of libs/session.php, libs/socket.php, +libs/model/schema.php and libs/model/behavior.php have been renamed +so that there is a better mapping between filenames and main +classes contained within (as well as dealing with some name-spacing +issues): + + +- session.php -> cake\_session.php + + + - App::import('Core', 'Session') -> App::import('Core', + 'CakeSession') + +- socket.php -> cake\_socket.php + + + - App::import('Core', 'Socket') -> App::import('Core', + 'CakeSocket') + +- schema.php -> cake\_schema.php + + + - App::import('Model', 'Schema') -> App::import('Model', + 'CakeSchema') + +- behavior.php -> model\_behavior.php + + + - App::import('Core', 'Behavior') -> App::import('Core', + 'ModelBehavior') + + +In most cases, the above renaming will not affect userland code. + +**Inheritance from Object** + +The following classes no longer extend Object: + + +- Router +- Set +- Inflector +- Cache +- CacheEngine + +If you were using Object methods from these classes, you will need +to not use those methods. + +Controller & Components +~~~~~~~~~~~~~~~~~~~~~~~ + +**Controller** + + +- ``Controller::set()`` no longer changes variables from + ``$var_name`` to ``$varName``. Variables always appear in the view + exactly as you set them. + +- ``Controller::set('title', $var)`` no longer sets + ``$title_for_layout`` when rendering the layout. + ``$title_for_layout`` is still populated by default. But if you + want to customize it, use + ``$this->set('title_for_layout', $var)``. + +- ``Controller::$pageTitle`` has been removed. Use + ``$this->set('title_for_layout', $var);`` instead. + +- Controller has two new methods ``startupProcess`` and + ``shutdownProcess``. These methods are responsible for handling the + controller startup and shutdown processes. + +**Component** + + +- ``Component::triggerCallback`` has been added. It is a generic + hook into the component callback process. It supplants + ``Component::startup()``, ``Component::shutdown()`` and + ``Component::beforeRender()`` as the preferred way to trigger + callbacks. + +**CookieComponent** + + +- ``del`` is deprecated use ``delete`` + +**AclComponent + DbAcl** + +Node reference checks done with paths are now less greedy and will +no longer consume intermediary nodes when doing searches. In the +past given the structure: + +:: + + ROOT/ + Users/ + Users/ + edit + +The path ``ROOT/Users`` would match the last Users node instead of +the first. In 1.3, if you were expecting to get the last node you +would need to use the path ``ROOT/Users/Users`` + +**RequestHandlerComponent** + + +- ``getReferrer`` is deprecated use ``getReferer`` + +**SessionComponent & SessionHelper** + + +- ``del`` is deprecated use ``delete`` + +``SessionComponent::setFlash()`` second param used to be used for +setting the layout and accordingly rendered a layout file. This has +been modified to use an element. If you specified custom session +flash layouts in your applications you will need to make the +following changes. + + +#. Move the required layout files into app/views/elements +#. Rename the $content\_for\_layout variable to $message +#. Make sure you have ``echo $session->flash();`` in your layout + +``SessionComponent`` and ``SessionHelper`` are not automatically +loaded. +Both ``SessionComponent`` and ``SessionHelper`` are no longer +automatically included without you asking for them. SessionHelper +and SessionComponent now act like every other component and must be +declared like any other helper/component. You should update +``AppController::$components`` and ``AppController::$helpers`` to +include these classes to retain existing behavior:: + + var $components = array('Session', 'Auth', ...); + var $helpers = array('Session', 'Html', 'Form' ...); + +These change were done to make CakePHP more explicit and +declarative in what classes you the application developer want to +use. In the past there was no way to avoid loading the Session +classes without modifying core files. Which is something we want +you to be able to avoid. In addition Session classes were the only +magical component and helper. This change helps unify and normalize +behavior amongst all classes. + +Library Classes +~~~~~~~~~~~~~~~ + +**CakeSession** + + +- ``del`` is deprecated use ``delete`` + +**SessionComponent** + + +- ``SessionComponent::setFlash()`` now uses an *element* instead + of a *layout* as its second parameter. Be sure to move any flash + layouts from app/views/layouts to app/views/elements and change + instances of $content\_for\_layout to $message. + +**Folder** + + +- ``mkdir`` is deprecated use ``create`` +- ``mv`` is deprecated use ``move`` +- ``ls`` is deprecated use ``read`` +- ``cp`` is deprecated use ``copy`` +- ``rm`` is deprecated use ``delete`` + +**Set** + + +- ``isEqual`` is deprecated. Use == or ===. + +**String** + + +- ``getInstance`` is deprecated, call String methods statically. + +**Router** + +``Routing.admin`` is deprecated. It provided an inconsistent +behavior with other prefix style routes in that it was treated +differently. Instead you should use ``Routing.prefixes``. Prefix +routes in 1.3 do not require additional routes to be declared +manually. All prefix routes will be generated automatically. To +update simply change your core.php:: + + //from: + Configure::write('Routing.admin', 'admin'); + + //to: + Configure::write('Routing.prefixes', array('admin')); + +See the New features guide for more information on using prefix +routes. A small change has also been done to routing params. Routed +params should now only consist of alphanumeric chars, - and \_ or +``/[A-Z0-9-_+]+/``:: + + Router::connect('/:$%@#param/:action/*', array(...)); // BAD + Router::connect('/:can/:anybody/:see/:m-3/*', array(...)); //Acceptable + +For 1.3 the internals of the Router were heavily refactored to +increase performance and reduce code clutter. The side effect of +this is two seldom used features were removed, as they were +problematic and buggy even with the existing code base. First path +segments using full regular expressions was removed. You can no +longer create routes like:: + + Router::connect( + '/([0-9]+)-p-(.*)/', + array('controller' => 'products', 'action' => 'show') + ); + +These routes complicated route compilation and impossible to +reverse route. If you need routes like this, it is recommended that +you use route parameters with capture patterns. Next mid-route +greedy star support has been removed. It was previously possible to +use a greedy star in the middle of a route:: + + Router::connect( + '/pages/*/:event', + array('controller' => 'pages', 'action' => 'display'), + array('event' => '[a-z0-9_-]+') + ); + +This is no longer supported as mid-route greedy stars behaved +erratically, and complicated route compiling. Outside of these two +edge-case features and the above changes the router behaves exactly +as it did in 1.2 + +Also, people using the 'id' key in array-form URLs will notice that +Router::url() now treats this as a named parameter. If you +previously used this approach for passing the ID parameter to +actions, you will need to rewrite all your $html->link() and +$this->redirect() calls to reflect this change. + +:: + + // old format: + $url = array('controller' => 'posts', 'action' => 'view', 'id' => $id); + // use cases: + Router::url($url); + $html->link($url); + $this->redirect($url); + // 1.2 result: + /posts/view/123 + // 1.3 result: + /posts/view/id:123 + // correct format: + $url = array('controller' => 'posts', 'action' => 'view', $id); + +**Dispatcher** + +``Dispatcher`` is no longer capable of setting a controller's +layout/viewPath with request parameters. Control of these +properties should be handled by the Controller, not the Dispatcher. +This feature was also undocumented, and untested. + +**Debugger** + + +- ``Debugger::checkSessionKey()`` has been renamed to + ``Debugger::checkSecurityKeys()`` +- Calling ``Debugger::output("text")`` no longer works. Use + ``Debugger::output("txt")``. + +**Object** + + +- ``Object::$_log`` has been removed. ``CakeLog::write`` is now + called statically. See :doc:`/core-libraries/logging` + for more information on changes made to logging. + +**Sanitize** + + +- ``Sanitize::html()`` now actually always returns escaped + strings. In the past using the ``$remove`` parameter would skip + entity encoding, returning possibly dangerous content. +- ``Sanitize::clean()`` now has a ``remove_html`` option. This + will trigger the ``strip_tags`` feature of ``Sanitize::html()``, + and must be used in conjunction with the ``encode`` parameter. + +**Configure and App** + + +- Configure::listObjects() replaced by App::objects() +- Configure::corePaths() replaced by App::core() +- Configure::buildPaths() replaced by App::build() +- Configure no longer manages paths. +- Configure::write('modelPaths', array...) replaced by + App::build(array('models' => array...)) +- Configure::read('modelPaths') replaced by App::path('models') +- There is no longer a debug = 3. The controller dumps generated + by this setting often caused memory consumption issues making it an + impractical and unusable setting. The ``$cakeDebug`` variable has + also been removed from ``View::renderLayout`` You should remove + this variable reference to avoid errors. +- ``Configure::load()`` can now load configuration files from + plugins. Use ``Configure::load('plugin.file');`` to load + configuration files from plugins. Any configuration files in your + application that use ``.`` in the name should be updated to use + ``_`` + +**Cache** + +In addition to being able to load CacheEngines from app/libs or +plugins, Cache underwent some refactoring for CakePHP1.3. These +refactorings focused around reducing the number and frequency of +method calls. The end result was a significant performance +improvement with only a few minor API changes which are detailed +below. + +The changes in Cache removed the singletons used for each Engine +type, and instead an engine instance is made for each unique key +created with ``Cache::config()``. Since engines are not singletons +anymore, ``Cache::engine()`` was not needed and was removed. In +addition ``Cache::isInitialized()`` now checks cache +*configuration names*, not cache *engine names*. You can still use +``Cache::set()`` or ``Cache::engine()`` to modify cache +configurations. Also checkout the +:doc:`/appendices/new-features-in-cakephp-1-3` for +more information on the additional methods added to ``Cache``. + +It should be noted that using an app/libs or plugin cache engine +for the default cache config can cause performance issues as the +import that loads these classes will always be uncached. It is +recommended that you either use one of the core cache engines for +your ``default`` configuration, or manually include the cache +engine class before configuring it. Furthermore any non-core cache +engine configurations should be done in +``app/config/bootstrap.php`` for the same reasons detailed above. + +Model Databases and Datasources +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Model** + + +- ``Model::del()`` and ``Model::remove()`` have been removed in + favor of ``Model::delete()``, which is now the canonical delete + method. +- ``Model::findAll``, findCount, findNeighbours, removed. +- Dynamic calling of setTablePrefix() has been removed. + tableprefix should be with the ``$tablePrefix`` property, and any + other custom construction behavior should be done in an overridden + ``Model::__construct()``. +- ``DboSource::query()`` now throws warnings for un-handled model + methods, instead of trying to run them as queries. This means, + people starting transactions improperly via the + ``$this->Model->begin()`` syntax will need to update their code so + that it accesses the model's DataSource object directly. +- Missing validation methods will now trigger errors in + development mode. +- Missing behaviors will now trigger a cakeError. +- ``Model::find(first)`` will no longer use the id property for + default conditions if no conditions are supplied and id is not + empty. Instead no conditions will be used +- For Model::saveAll() the default value for option 'validate' is + now 'first' instead of true + +**Datasources** + + +- DataSource::exists() has been refactored to be more consistent + with non-database backed datasources. Previously, if you set + ``var $useTable = false; var $useDbConfig = 'custom';``, it was + impossible for ``Model::exists()`` to return anything but false. + This prevented custom datasources from using ``create()`` or + ``update()`` correctly without some ugly hacks. If you have custom + datasources that implement ``create()``, ``update()``, and + ``read()`` (since ``Model::exists()`` will make a call to + ``Model::find('count')``, which is passed to + ``DataSource::read()``), make sure to re-run your unit tests on + 1.3. + +**Databases** + +Most database configurations no longer support the 'connect' key +(which has been deprecated since pre-1.2). Instead, set +``'persistent' => true`` or false to determine whether or not a +persistent database connection should be used + +**SQL log dumping** + +A commonly asked question is how can one disable or remove the SQL +log dump at the bottom of the page?. In previous versions the HTML +SQL log generation was buried inside DboSource. For 1.3 there is a +new core element called ``sql_dump``. ``DboSource`` no longer +automatically outputs SQL logs. If you want to output SQL logs in +1.3, do the following: + +:: + + echo $this->element('sql_dump'); + +You can place this element anywhere in your layout or view. The +``sql_dump`` element will only generate output when +``Configure::read('debug')`` is equal to 2. You can of course +customize or override this element in your app by creating +``app/views/elements/sql_dump.ctp``. + +View and Helpers +~~~~~~~~~~~~~~~~ + +**View** + + +- ``View::renderElement`` removed. Use ``View::element()`` + instead. +- Automagic support for ``.thtml`` view file extension has been + removed either declare ``$this->ext = 'thtml';`` in your + controllers, or rename your views to use ``.ctp`` +- ``View::set('title', $var)`` no longer sets + ``$title_for_layout`` when rendering the layout. + ``$title_for_layout`` is still populated by default. But if you + want to customize it, use ``$this->set('title_for_layout', $var)``. +- ``View::$pageTitle`` has been removed. Use + ``$this->set('title_for_layout', $var);`` instead. +- The ``$cakeDebug`` layout variable associated with debug = 3 has + been removed. Remove it from your layouts as it will cause errors. + Also see the notes related to SQL log dumping and Configure for + more information. + +All core helpers no longer use ``Helper::output()``. The method was +inconsistently used and caused output issues with many of +FormHelper's methods. If you previously overrode +``AppHelper::output()`` to force helpers to auto-echo you will need +to update your view files to manually echo helper output. + +**TextHelper** + + +- ``TextHelper::trim()`` is deprecated, used ``truncate()`` + instead. +- ``TextHelper::highlight()`` no longer has: +- an ``$highlighter`` parameter. Use ``$options['format']`` + instead. +- an ``$considerHtml``parameter. Use ``$options['html']`` instead. +- ``TextHelper::truncate()`` no longer has: +- an ``$ending`` parameter. Use ``$options['ending']`` instead. +- an ``$exact`` parameter. Use ``$options['exact']`` instead. +- an ``$considerHtml``parameter. Use ``$options['html']`` + instead. + +**PaginatorHelper** + +PaginatorHelper has had a number of enhancements applied to make +styling easier. +``prev()``, ``next()``, ``first()`` and ``last()`` + +The disabled state of these methods now defaults to ```` tags +instead of ``
`` tags. + +passedArgs are now auto merged with URL options in paginator. + +``sort()``, ``prev()``, ``next()`` now add additional class names +to the generated html. ``prev()`` adds a class of prev. ``next()`` +adds a class of next. ``sort()`` will add the direction currently +being sorted, either asc or desc. + +**FormHelper** + + +- ``FormHelper::dateTime()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::year()`` no longer has a ``$showEmpty`` parameter. + Use ``$attributes['empty']`` instead. +- ``FormHelper::month()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::day()`` no longer has a ``$showEmpty`` parameter. + Use ``$attributes['empty']`` instead. +- ``FormHelper::minute()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::meridian()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- ``FormHelper::select()`` no longer has a ``$showEmpty`` + parameter. Use ``$attributes['empty']`` instead. +- Default URLs generated by form helper no longer contain 'id' + parameter. This makes default URLs more consistent with documented + userland routes. Also enables reverse routing to work in a more + intuitive fashion with default FormHelper URLs. +- ``FormHelper::submit()`` Can now create other types of inputs + other than type=submit. Use the type option to control the type of + input generated. +- ``FormHelper::button()`` Now creates `` + + + + + + The ``button`` input type supports the ``escape`` option, which accepts a + bool and determines whether to HTML entity encode the $title of the button. + Defaults to false:: + + echo $this->Form->button('Submit Form', array( + 'type' => 'submit', + 'escape' => true + )); + +.. php:method:: postButton(string $title, mixed $url, array $options = array ()) + + Create a ``