diff --git a/en/appendices.rst b/en/appendices.rst index 436a311df4..64bf718a76 100644 --- a/en/appendices.rst +++ b/en/appendices.rst @@ -4,13 +4,13 @@ Appendices Appendices contain information regarding the new features introduced in each version and the migration path between versions. -3.x Migration Guide +4.x Migration Guide =================== .. toctree:: :maxdepth: 1 - appendices/3-x-migration-guide + appendices/4-0-migration-guide General Information =================== diff --git a/en/appendices/3-0-migration-guide.rst b/en/appendices/3-0-migration-guide.rst deleted file mode 100644 index 1fe5dacf99..0000000000 --- a/en/appendices/3-0-migration-guide.rst +++ /dev/null @@ -1,1275 +0,0 @@ -3.0 Migration Guide -################### - -This page summarizes the changes from CakePHP 2.x that will assist in migrating -a project to 3.0, as well as a reference to get up to date with the changes made -to the core since the CakePHP 2.x branch. Be sure to read the other pages in -this guide for all the new features and API changes. - -Requirements -============ - -- CakePHP 3.x supports PHP Version 5.4.16 and above. -- CakePHP 3.x requires the mbstring extension. -- CakePHP 3.x requires the intl extension. - -.. warning:: - - CakePHP 3.0 will not work if you do not meet the above requirements. - -Upgrade Tool -============ - -While this document covers all the breaking changes and improvements made in -CakePHP 3.0, we've also created a console application to help you complete some -of the time consuming mechanical changes. You can `get the upgrade tool from -github `_. - -Application Directory Layout -============================ - -The application directory layout has changed and now follows -`PSR-4 `_. You should use the -`app skeleton `_ project as a reference point -when updating your application. - -CakePHP should be installed with Composer -========================================= - -Since CakePHP can no longer be installed via PEAR, or in a shared -directory, those options are no longer supported. Instead you should use -`Composer `_ to install CakePHP into your application. - -Namespaces -========== - -All of CakePHP's core classes are now namespaced and follow PSR-4 autoloading -specifications. For example **src/Cache/Cache.php** is namespaced as -``Cake\Cache\Cache``. Global constants and helper methods like :php:meth:`__()` -and :php:meth:`debug()` are not namespaced for convenience sake. - -Removed Constants -================= - -The following deprecated constants have been removed: - -* ``IMAGES`` -* ``CSS`` -* ``JS`` -* ``IMAGES_URL`` -* ``JS_URL`` -* ``CSS_URL`` -* ``DEFAULT_LANGUAGE`` - -Configuration -============= - -Configuration in CakePHP 3.0 is significantly different than in previous -versions. You should read the :doc:`/development/configuration` documentation -for how configuration is done in 3.0. - -You can no longer use ``App::build()`` to configure additional class paths. -Instead you should map additional paths using your application's autoloader. See -the section on :ref:`additional-class-paths` for more information. - -Three new configure variables provide the path configuration for plugins, -views and locale files. You can add multiple paths to ``App.paths.templates``, -``App.paths.plugins``, ``App.paths.locales`` to configure multiple paths for -templates, plugins and locale files respectively. - -The config key ``www_root`` has been changed to ``wwwRoot`` for consistency. Please adjust -your **app.php** config file as well as any usage of ``Configure::read('App.wwwRoot')``. - -New ORM -======= - -CakePHP 3.0 features a new ORM that has been re-built from the ground up. The -new ORM is significantly different and incompatible with the previous one. -Upgrading to the new ORM will require extensive changes in any application that -is being upgraded. See the new :doc:`/orm` documentation for information on how -to use the new ORM. - -Basics -====== - -* ``LogError()`` was removed, it provided no benefit and is rarely/never used. -* The following global functions have been removed: ``config()``, ``cache()``, - ``clearCache()``, ``convertSlashes()``, ``am()``, ``fileExistsInPath()``, - ``sortByKey()``. - -Debugging -========= - -* ``Configure::write('debug', $bool)`` does not support 0/1/2 anymore. A simple boolean - is used instead to switch debug mode on or off. - -Object settings/configuration -============================= - -* Objects used in CakePHP now have a consistent instance-configuration storage/retrieval - system. Code which previously accessed for example: ``$object->settings`` should instead - be updated to use ``$object->config()``. - -Cache -===== - -* ``Memcache`` engine has been removed, use :php:class:`Cake\\Cache\\Cache\\Engine\\Memcached` instead. -* Cache engines are now lazy loaded upon first use. -* :php:meth:`Cake\\Cache\\Cache::engine()` has been added. -* :php:meth:`Cake\\Cache\\Cache::enabled()` has been added. This replaced the - ``Cache.disable`` configure option. -* :php:meth:`Cake\\Cache\\Cache::enable()` has been added. -* :php:meth:`Cake\\Cache\\Cache::disable()` has been added. -* Cache configurations are now immutable. If you need to change configuration - you must first drop the configuration and then re-create it. This prevents - synchronization issues with configuration options. -* ``Cache::set()`` has been removed. It is recommended that you create multiple - cache configurations to replace runtime configuration tweaks previously - possible with ``Cache::set()``. -* All ``CacheEngine`` subclasses now implement a ``config()`` method. -* :php:meth:`Cake\\Cache\\Cache::readMany()`, :php:meth:`Cake\\Cache\\Cache::deleteMany()`, - and :php:meth:`Cake\\Cache\\Cache::writeMany()` were added. - -All :php:class:`Cake\\Cache\\Cache\\CacheEngine` methods now honor/are responsible for handling the -configured key prefix. The :php:meth:`Cake\\Cache\\CacheEngine::write()` no longer permits setting -the duration on write - the duration is taken from the cache engine's runtime config. Calling a -cache method with an empty key will now throw an :php:class:`InvalidArgumentException`, instead -of returning ``false``. - -Core -==== - -App ---- - -- ``App::pluginPath()`` has been removed. Use ``CakePlugin::path()`` instead. -- ``App::build()`` has been removed. -- ``App::location()`` has been removed. -- ``App::paths()`` has been removed. -- ``App::load()`` has been removed. -- ``App::objects()`` has been removed. -- ``App::RESET`` has been removed. -- ``App::APPEND`` has been removed. -- ``App::PREPEND`` has been removed. -- ``App::REGISTER`` has been removed. - -Plugin ------- - -- :php:meth:`Cake\\Core\\Plugin::load()` does not setup an autoloader unless - you set the ``autoload`` option to ``true``. -- When loading plugins you can no longer provide a callable. -- When loading plugins you can no longer provide an array of config files to - load. - -Configure ---------- - -- ``Cake\Configure\PhpReader`` renamed to - :php:class:`Cake\\Core\\Configure\\Engine\PhpConfig` -- ``Cake\Configure\IniReader`` renamed to - :php:class:`Cake\\Core\\Configure\\Engine\IniConfig` -- ``Cake\Configure\ConfigReaderInterface`` renamed to - :php:class:`Cake\\Core\\Configure\\ConfigEngineInterface` -- :php:meth:`Cake\\Core\\Configure::consume()` was added. -- :php:meth:`Cake\\Core\\Configure::load()` now expects the file name without - extension suffix as this can be derived from the engine. E.g. using PhpConfig - use ``app`` to load **app.php**. -- Setting a ``$config`` variable in PHP config file is deprecated. - :php:class:`Cake\\Core\\Configure\\Engine\PhpConfig` now expects the config - file to return an array. -- A new config engine :php:class:`Cake\\Core\\Configure\\Engine\JsonConfig` has - been added. - -Object ------- - -The ``Object`` class has been removed. It formerly contained a grab bag of -methods that were used in various places across the framework. The most useful -of these methods have been extracted into traits. You can use the -:php:trait:`Cake\\Log\\LogTrait` to access the ``log()`` method. The -:php:trait:`Cake\\Routing\\RequestActionTrait` provides ``requestAction()``. - -Console -======= - -The ``cake`` executable has been moved from the **app/Console** directory to the -**bin** directory within the application skeleton. You can now invoke CakePHP's -console with ``bin/cake``. - -TaskCollection Replaced ------------------------ - -This class has been renamed to :php:class:`Cake\\Console\\TaskRegistry`. -See the section on :doc:`/core-libraries/registry-objects` for more information -on the features provided by the new class. You can use the ``cake upgrade -rename_collections`` to assist in upgrading your code. Tasks no longer have -access to callbacks, as there were never any callbacks to use. - -Shell ------ - -- ``Shell::__construct()`` has changed. It now takes an instance of - :php:class:`Cake\\Console\\ConsoleIo`. -- ``Shell::param()`` has been added as convenience access to the parameters. - -Additionally all shell methods will be transformed to camel case when invoked. -For example, if you had a ``hello_world()`` method inside a shell and invoked it -with ``bin/cake my_shell hello_world``, you will need to rename the method -to ``helloWorld``. There are no changes required in the way you invoke commands. - -ConsoleOptionParser -------------------- - -- ``ConsoleOptionParser::merge()`` has been added to merge parsers. - -ConsoleInputArgument --------------------- - -- ``ConsoleInputArgument::isEqualTo()`` has been added to compare two arguments. - -Shell / Task -============ - -Shells and Tasks have been moved from ``Console/Command`` and -``Console/Command/Task`` to ``Shell`` and ``Shell/Task``. - -ApiShell Removed ----------------- - -The ApiShell was removed as it didn't provide any benefit over the file source -itself and the online documentation/`API `_. - -SchemaShell Removed -------------------- - -The SchemaShell was removed as it was never a complete database migration implementation -and better tools such as `Phinx `_ have emerged. It has been replaced by -the `CakePHP Migrations Plugin `_ which acts as a wrapper between -CakePHP and `Phinx `_. - -ExtractTask ------------ - -- ``bin/cake i18n extract`` no longer includes untranslated validation - messages. If you want translated validation messages you should wrap those - messages in `__()` calls like any other content. - -BakeShell / TemplateTask ------------------------- - -- Bake is no longer part of the core source and is superseded by - `CakePHP Bake Plugin `_ -- Bake templates have been moved under **src/Template/Bake**. -- The syntax of Bake templates now uses erb-style tags (``<% %>``) to denote - templating logic, allowing php code to be treated as plain text. -- The ``bake view`` command has been renamed ``bake template``. - -Event -===== - -The ``getEventManager()`` method, was removed on all objects that had it. An -``eventManager()`` method is now provided by the ``EventManagerTrait``. The -``EventManagerTrait`` contains the logic of instantiating and keeping -a reference to a local event manager. - -The Event subsystem has had a number of optional features removed. When -dispatching events you can no longer use the following options: - -* ``passParams`` This option is now enabled always implicitly. You - cannot turn it off. -* ``break`` This option has been removed. You must now stop events. -* ``breakOn`` This option has been removed. You must now stop events. - -Log -=== - -* Log configurations are now immutable. If you need to change configuration - you must first drop the configuration and then re-create it. This prevents - synchronization issues with configuration options. -* Log engines are now lazily loaded upon the first write to the logs. -* :php:meth:`Cake\\Log\\Log::engine()` has been added. -* The following methods have been removed from :php:class:`Cake\\Log\\Log` :: - ``defaultLevels()``, ``enabled()``, ``enable()``, ``disable()``. -* You can no longer create custom levels using ``Log::levels()``. -* When configuring loggers you should use ``'levels'`` instead of ``'types'``. -* You can no longer specify custom log levels. You must use the default set of - log levels. You should use logging scopes to create custom log files or - specific handling for different sections of your application. Using - a non-standard log level will now throw an exception. -* :php:trait:`Cake\\Log\\LogTrait` was added. You can use this trait in your - classes to add the ``log()`` method. -* The logging scope passed to :php:meth:`Cake\\Log\\Log::write()` is now - forwarded to the log engines' ``write()`` method in order to provide better - context to the engines. -* Log engines are now required to implement ``Psr\Log\LogInterface`` instead of - Cake's own ``LogInterface``. In general, if you extended :php:class:`Cake\\Log\\Engine\\BaseEngine` - you just need to rename the ``write()`` method to ``log()``. -* :php:meth:`Cake\\Log\\Engine\\FileLog` now writes files in ``ROOT/logs`` instead of ``ROOT/tmp/logs``. - -Routing -======= - -Named Parameters ----------------- - -Named parameters were removed in 3.0. Named parameters were added in 1.2.0 as -a 'pretty' version of query string parameters. While the visual benefit is -arguable, the problems named parameters created are not. - -Named parameters required special handling in CakePHP as well as any PHP or -JavaScript library that needed to interact with them, as named parameters are -not implemented or understood by any library *except* CakePHP. The additional -complexity and code required to support named parameters did not justify their -existence, and they have been removed. In their place you should use standard -query string parameters or passed arguments. By default ``Router`` will treat -any additional parameters to ``Router::url()`` as query string arguments. - -Since many applications will still need to parse incoming URLs containing named -parameters. :php:meth:`Cake\\Routing\\Router::parseNamedParams()` has -been added to allow backwards compatibility with existing URLs. - -RequestActionTrait ------------------- - -- :php:meth:`Cake\\Routing\\RequestActionTrait::requestAction()` has had - some of the extra options changed: - - - ``options[url]`` is now ``options[query]``. - - ``options[data]`` is now ``options[post]``. - - Named parameters are no longer supported. - -Router ------- - -* Named parameters have been removed, see above for more information. -* The ``full_base`` option has been replaced with the ``_full`` option. -* The ``ext`` option has been replaced with the ``_ext`` option. -* ``_scheme``, ``_port``, ``_host``, ``_base``, ``_full``, ``_ext`` options added. -* String URLs are no longer modified by adding the plugin/controller/prefix names. -* The default fallback route handling was removed. If no routes - match a parameter set ``/`` will be returned. -* Route classes are responsible for *all* URL generation including - query string parameters. This makes routes far more powerful and flexible. -* Persistent parameters were removed. They were replaced with - :php:meth:`Cake\\Routing\\Router::urlFilter()` which allows - a more flexible way to mutate URLs being reverse routed. -* ``Router::parseExtensions()`` has been removed. - Use :php:meth:`Cake\\Routing\\Router::extensions()` instead. This method - **must** be called before routes are connected. It won't modify existing - routes. -* ``Router::setExtensions()`` has been removed. - Use :php:meth:`Cake\\Routing\\Router::extensions()` instead. -* ``Router::resourceMap()`` has been removed. -* The ``[method]`` option has been renamed to ``_method``. -* The ability to match arbitrary headers with ``[]`` style parameters has been - removed. If you need to parse/match on arbitrary conditions consider using - custom route classes. -* ``Router::promote()`` has been removed. -* ``Router::parse()`` will now raise an exception when a URL cannot be handled - by any route. -* ``Router::url()`` will now raise an exception when no route matches a set of - parameters. -* Routing scopes have been introduced. Routing scopes allow you to keep your - routes file DRY and give Router hints on how to optimize parsing & reverse - routing URLs. - -Route ------ - -* ``CakeRoute`` was re-named to ``Route``. -* The signature of ``match()`` has changed to ``match($url, $context = [])`` - See :php:meth:`Cake\\Routing\\Route::match()` for information on the new signature. - -Dispatcher Filters Configuration Changed ----------------------------------------- - -Dispatcher filters are no longer added to your application using ``Configure``. -You now append them with :php:class:`Cake\\Routing\\DispatcherFactory`. This -means if your application used ``Dispatcher.filters``, you should now use -:php:meth:`Cake\\Routing\\DispatcherFactory::add()`. - -In addition to configuration changes, dispatcher filters have had some -conventions updated, and features added. See the -:doc:`/development/dispatch-filters` documentation for more information. - -Filter\AssetFilter ------------------- - -* Plugin & theme assets handled by the AssetFilter are no longer read via - ``include`` instead they are treated as plain text files. This fixes a number - of issues with JavaScript libraries like TinyMCE and environments with - short_tags enabled. -* Support for the ``Asset.filter`` configuration and hooks were removed. This - feature should be replaced with a plugin or dispatcher filter. - -Network -======= - -Request -------- - -* ``CakeRequest`` has been renamed to :php:class:`Cake\\Network\\Request`. -* :php:meth:`Cake\\Network\\Request::port()` was added. -* :php:meth:`Cake\\Network\\Request::scheme()` was added. -* :php:meth:`Cake\\Network\\Request::cookie()` was added. -* :php:attr:`Cake\\Network\\Request::$trustProxy` was added. This makes it easier to put - CakePHP applications behind load balancers. -* :php:attr:`Cake\\Network\\Request::$data` is no longer merged with the prefixed data - key, as that prefix has been removed. -* :php:meth:`Cake\\Network\\Request::env()` was added. -* :php:meth:`Cake\\Network\\Request::acceptLanguage()` was changed from static method - to non-static. -* Request detector for "mobile" has been removed from the core. Instead the app - template adds detectors for "mobile" and "tablet" using ``MobileDetect`` lib. -* The method ``onlyAllow()`` has been renamed to ``allowMethod()`` and no longer accepts "var args". - All method names need to be passed as first argument, either as string or array of strings. - -Response --------- - -* The mapping of mimetype ``text/plain`` to extension ``csv`` has been removed. - As a consequence :php:class:`Cake\\Controller\\Component\\RequestHandlerComponent` - doesn't set extension to ``csv`` if ``Accept`` header contains mimetype ``text/plain`` - which was a common annoyance when receiving a jQuery XHR request. - -Sessions -======== - -The session class is no longer static, instead the session can be accessed -through the request object. See the :doc:`/development/sessions` documentation -for using the session object. - -* :php:class:`Cake\\Network\\Session` and related session classes have been - moved under the ``Cake\Network`` namespace. -* ``SessionHandlerInterface`` has been removed in favor of the one provided by - PHP itself. -* The property ``Session::$requestCountdown`` has been removed. -* The session checkAgent feature has been removed. It caused a number of bugs - when chrome frame, and flash player are involved. -* The conventional sessions database table name is now ``sessions`` instead of - ``cake_sessions``. -* The session cookie timeout is automatically updated in tandem with the timeout - in the session data. -* The path for session cookie now defaults to app's base path instead of "/". - A new configuration variable ``Session.cookiePath`` has been added to - customize the cookie path. -* A new convenience method :php:meth:`Cake\\Network\\Session::consume()` has been added - to allow reading and deleting session data in a single step. -* The default value of :php:meth:`Cake\\Network\\Session::clear()`'s argument ``$renew`` has been changed - from ``true`` to ``false``. - -Network\\Http -============= - -* ``HttpSocket`` is now :php:class:`Cake\\Network\\Http\\Client`. -* Http\Client has been re-written from the ground up. It has a simpler/easier to - use API, support for new authentication systems like OAuth, and file uploads. - It uses PHP's stream APIs so there is no requirement for cURL. See the - :doc:`/core-libraries/httpclient` documentation for more information. - -Network\\Email -============== - -* :php:meth:`Cake\\Network\\Email\\Email::config()` is now used to define - configuration profiles. This replaces the ``EmailConfig`` classes in previous - versions. -* :php:meth:`Cake\\Network\\Email\\Email::profile()` replaces ``config()`` as - the way to modify per instance configuration options. -* :php:meth:`Cake\\Network\\Email\\Email::drop()` has been added to allow the - removal of email configuration. -* :php:meth:`Cake\\Network\\Email\\Email::configTransport()` has been added to allow the - definition of transport configurations. This change removes transport options - from delivery profiles and allows you to re-use transports across email - profiles. -* :php:meth:`Cake\\Network\\Email\\Email::dropTransport()` has been added to allow the - removal of transport configuration. - -Controller -========== - -Controller ----------- - -- The ``$helpers``, ``$components`` properties are now merged - with **all** parent classes not just ``AppController`` and the plugin - AppController. The properties are merged differently now as well. Instead of - all settings in all classes being merged together, the configuration defined - in the child class will be used. This means that if you have some - configuration defined in your AppController, and some configuration defined in - a subclass, only the configuration in the subclass will be used. -- ``Controller::httpCodes()`` has been removed, use - :php:meth:`Cake\\Network\\Response::httpCodes()` instead. -- ``Controller::disableCache()`` has been removed, use - :php:meth:`Cake\\Network\\Response::disableCache()` instead. -- ``Controller::flash()`` has been removed. This method was rarely used in real - applications and served no purpose anymore. -- ``Controller::validate()`` and ``Controller::validationErrors()`` have been - removed. They were left over methods from the 1.x days where the concerns of - models + controllers were far more intertwined. -- ``Controller::loadModel()`` now loads table objects. -- The ``Controller::$scaffold`` property has been removed. Dynamic scaffolding - has been removed from CakePHP core. An improved scaffolding plugin, named CRUD, can be found here: https://github.com/FriendsOfCake/crud -- The ``Controller::$ext`` property has been removed. You now have to extend and - override the ``View::$_ext`` property if you want to use a non-default view file - extension. -- The ``Controller::$methods`` property has been removed. You should now use - ``Controller::isAction()`` to determine whether or not a method name is an - action. This change was made to allow easier customization of what is and is - not counted as an action. -- The ``Controller::$Components`` property has been removed and replaced with - ``_components``. If you need to load components at runtime you should use - ``$this->loadComponent()`` on your controller. -- The signature of :php:meth:`Cake\\Controller\\Controller::redirect()` has been - changed to ``Controller::redirect(string|array $url, int $status = null)``. - The 3rd argument ``$exit`` has been dropped. The method can no longer send - response and exit script, instead it returns a ``Response`` instance with - appropriate headers set. -- The ``base``, ``webroot``, ``here``, ``data``, ``action``, and ``params`` - magic properties have been removed. You should access all of these properties - on ``$this->request`` instead. -- Underscore prefixed controller methods like ``_someMethod()`` are no longer - treated as private methods. Use proper visibility keywords instead. Only - public methods can be used as controller actions. - -Scaffold Removed ----------------- - -The dynamic scaffolding in CakePHP has been removed from CakePHP core. It was -infrequently used, and never intended for production use. An improved -scaffolding plugin, named CRUD, can be found here: -https://github.com/FriendsOfCake/crud - -ComponentCollection Replaced ----------------------------- - -This class has been renamed to :php:class:`Cake\\Controller\\ComponentRegistry`. -See the section on :doc:`/core-libraries/registry-objects` for more information -on the features provided by the new class. You can use the ``cake upgrade -rename_collections`` to assist in upgrading your code. - -Component ---------- - -* The ``_Collection`` property is now ``_registry``. It contains an instance - of :php:class:`Cake\\Controller\\ComponentRegistry` now. -* All components should now use the ``config()`` method to get/set - configuration. -* Default configuration for components should be defined in the - ``$_defaultConfig`` property. This property is automatically merged with any - configuration provided to the constructor. -* Configuration options are no longer set as public properties. -* The ``Component::initialize()`` method is no longer an event listener. - Instead, it is a post-constructor hook like ``Table::initialize()`` and - ``Controller::initialize()``. The new ``Component::beforeFilter()`` method is - bound to the same event that ``Component::initialize()`` used to be. The - initialize method should have the following signature ``initialize(array - $config)``. - -Controller\\Components -====================== - -CookieComponent ---------------- - -- Uses :php:meth:`Cake\\Network\\Request::cookie()` to read cookie data, - this eases testing, and allows for ControllerTestCase to set cookies. -- Cookies encrypted in previous versions of CakePHP using the ``cipher()`` method - are now un-readable because ``Security::cipher()`` has been removed. You will - need to re-encrypt cookies with the ``rijndael()`` or ``aes()`` method before upgrading. -- ``CookieComponent::type()`` has been removed and replaced with configuration - data accessed through ``config()``. -- ``write()`` no longer takes ``encryption`` or ``expires`` parameters. Both of - these are now managed through config data. See - :doc:`/controllers/components/cookie` for more information. -- The path for cookies now defaults to app's base path instead of "/". - -AuthComponent -------------- - -- ``Default`` is now the default password hasher used by authentication classes. - It uses exclusively the bcrypt hashing algorithm. If you want to continue using - SHA1 hashing used in 2.x use ``'passwordHasher' => 'Weak'`` in your authenticator configuration. -- A new ``FallbackPasswordHasher`` was added to help users migrate old passwords - from one algorithm to another. Check AuthComponent's documentation for more - info. -- ``BlowfishAuthenticate`` class has been removed. Just use ``FormAuthenticate`` -- ``BlowfishPasswordHasher`` class has been removed. Use - ``DefaultPasswordHasher`` instead. -- The ``loggedIn()`` method has been removed. Use ``user()`` instead. -- Configuration options are no longer set as public properties. -- The methods ``allow()`` and ``deny()`` no longer accept "var args". All method names need - to be passed as first argument, either as string or array of strings. -- The method ``login()`` has been removed and replaced by ``setUser()`` instead. - To login a user you now have to call ``identify()`` which returns user info upon - successful identification and then use ``setUser()`` to save the info to - session for persistence across requests. - -- ``BaseAuthenticate::_password()`` has been removed. Use a ``PasswordHasher`` - class instead. -- ``BaseAuthenticate::logout()`` has been removed. -- ``AuthComponent`` now triggers two events ``Auth.afterIdentify`` and - ``Auth.logout`` after a user has been identified and before a user is - logged out respectively. You can set callback functions for these events by - returning a mapping array from ``implementedEvents()`` method of your - authenticate class. - -ACL related classes were moved to a separate plugin. Password hashers, Authentication and -Authorization providers where moved to the ``\Cake\Auth`` namespace. You are -required to move your providers and hashers to the ``App\Auth`` namespace as -well. - -RequestHandlerComponent ------------------------ - -- The following methods have been removed from RequestHandler component:: - ``isAjax()``, ``isFlash()``, ``isSSL()``, ``isPut()``, ``isPost()``, ``isGet()``, ``isDelete()``. - Use the :php:meth:`Cake\\Network\\Request::is()` method instead with relevant argument. -- ``RequestHandler::setContent()`` was removed, use :php:meth:`Cake\\Network\\Response::type()` instead. -- ``RequestHandler::getReferer()`` was removed, use :php:meth:`Cake\\Network\\Request::referer()` instead. -- ``RequestHandler::getClientIP()`` was removed, use :php:meth:`Cake\\Network\\Request::clientIp()` instead. -- ``RequestHandler::getAjaxVersion()`` was removed. -- ``RequestHandler::mapType()`` was removed, use :php:meth:`Cake\\Network\\Response::mapType()` instead. -- Configuration options are no longer set as public properties. - -SecurityComponent ------------------ - -- The following methods and their related properties have been removed from Security component: - ``requirePost()``, ``requireGet()``, ``requirePut()``, ``requireDelete()``. - Use the :php:meth:`Cake\\Network\\Request::allowMethod()` instead. -- ``SecurityComponent::$disabledFields()`` has been removed, use - ``SecurityComponent::$unlockedFields()``. -- The CSRF related features in SecurityComponent have been extracted and moved - into a separate CsrfComponent. This allows you to use CSRF protection - without having to use form tampering prevention. -- Configuration options are no longer set as public properties. -- The methods ``requireAuth()`` and ``requireSecure()`` no longer accept "var args". - All method names need to be passed as first argument, either as string or array of strings. - -SessionComponent ----------------- - -- ``SessionComponent::setFlash()`` is deprecated. You should use - :doc:`/controllers/components/flash` instead. - -Error ------ - -Custom ExceptionRenderers are now expected to either return -a :php:class:`Cake\\Network\\Response` object or string when rendering errors. This means -that any methods handling specific exceptions must return a response or string -value. - -Model -===== - -The Model layer in 2.x has been entirely re-written and replaced. You should -review the :doc:`/appendices/orm-migration` for information on how to use the -new ORM. - -- The ``Model`` class has been removed. -- The ``BehaviorCollection`` class has been removed. -- The ``DboSource`` class has been removed. -- The ``Datasource`` class has been removed. -- The various datasource classes have been removed. - -ConnectionManager ------------------ - -- ConnectionManager has been moved to the ``Cake\Datasource`` namespace. -- ConnectionManager has had the following methods removed: - - - ``sourceList`` - - ``getSourceName`` - - ``loadDataSource`` - - ``enumConnectionObjects`` - -- :php:meth:`~Cake\\Database\\ConnectionManager::config()` has been added and is - now the only way to configure connections. -- :php:meth:`~Cake\\Database\\ConnectionManager::get()` has been added. It - replaces ``getDataSource()``. -- :php:meth:`~Cake\\Database\\ConnectionManager::configured()` has been added. It - and ``config()`` replace ``sourceList()`` & ``enumConnectionObjects()`` with - a more standard and consistent API. -- ``ConnectionManager::create()`` has been removed. - It can be replaced by ``config($name, $config)`` and ``get($name)``. - -Behaviors ---------- -- Underscore prefixed behavior methods like ``_someMethod()`` are no longer - treated as private methods. Use proper visibility keywords instead. - -TreeBehavior ------------- - -The TreeBehavior was completely re-written to use the new ORM. Although it works -the same as in 2.x, a few methods were renamed or removed: - -- ``TreeBehavior::children()`` is now a custom finder ``find('children')``. -- ``TreeBehavior::generateTreeList()`` is now a custom finder ``find('treeList')``. -- ``TreeBehavior::getParentNode()`` was removed. -- ``TreeBehavior::getPath()`` is now a custom finder ``find('path')``. -- ``TreeBehavior::reorder()`` was removed. -- ``TreeBehavior::verify()`` was removed. - -TestSuite -========= - -TestCase --------- - -- ``_normalizePath()`` has been added to allow path comparison tests to run across all - operation systems regarding their DS settings (``\`` in Windows vs ``/`` in UNIX, for example). - -The following assertion methods have been removed as they have long been deprecated and replaced by -their new PHPUnit counterpart: - -- ``assertEqual()`` in favor of ``assertEquals()`` -- ``assertNotEqual()`` in favor of ``assertNotEquals()`` -- ``assertIdentical()`` in favor of ``assertSame()`` -- ``assertNotIdentical()`` in favor of ``assertNotSame()`` -- ``assertPattern()`` in favor of ``assertRegExp()`` -- ``assertNoPattern()`` in favor of ``assertNotRegExp()`` -- ``assertReference()`` if favor of ``assertSame()`` -- ``assertIsA()`` in favor of ``assertInstanceOf()`` - -Note that some methods have switched the argument order, e.g. ``assertEqual($is, $expected)`` should now be -``assertEquals($expected, $is)``. - -The following assertion methods have been deprecated and will be removed in the future: - -- ``assertWithinMargin()`` in favor of ``assertWithinRange()`` -- ``assertTags()`` in favor of ``assertHtml()`` - -Both method replacements also switched the argument order for a consistent assert method API -with ``$expected`` as first argument. - -The following assertion methods have been added: - -- ``assertNotWithinRange()`` as counter part to ``assertWithinRange()`` - -View -==== - -Themes are now Basic Plugins ----------------------------- - -Having themes and plugins as ways to create modular application components has -proven to be limited, and confusing. In CakePHP 3.0, themes no longer reside -**inside** the application. Instead they are standalone plugins. This solves -a few problems with themes: - -- You could not put themes *in* plugins. -- Themes could not provide helpers, or custom view classes. - -Both these issues are solved by converting themes into plugins. - -View Folders Renamed --------------------- - -The folders containing view files now go under **src/Template** instead of **src/View**. -This was done to separate the view files from files containing php classes (eg. Helpers, View classes). - -The following View folders have been renamed to avoid naming collisions with controller names: - -- ``Layouts`` is now ``Layout`` -- ``Elements`` is now ``Element`` -- ``Errors`` is now ``Error`` -- ``Emails`` is now ``Email`` (same for ``Email`` inside ``Layout``) - -HelperCollection Replaced -------------------------- - -This class has been renamed to :php:class:`Cake\\View\\HelperRegistry`. -See the section on :doc:`/core-libraries/registry-objects` for more information -on the features provided by the new class. You can use the ``cake upgrade -rename_collections`` to assist in upgrading your code. - -View Class ----------- - -- The ``plugin`` key has been removed from ``$options`` argument of :php:meth:`Cake\\View\\View::element()`. - Specify the element name as ``SomePlugin.element_name`` instead. -- ``View::getVar()`` has been removed, use :php:meth:`Cake\\View\\View::get()` instead. -- ``View::$ext`` has been removed and instead a protected property ``View::$_ext`` - has been added. -- ``View::addScript()`` has been removed. Use :ref:`view-blocks` instead. -- The ``base``, ``webroot``, ``here``, ``data``, ``action``, and ``params`` - magic properties have been removed. You should access all of these properties - on ``$this->request`` instead. -- ``View::start()`` no longer appends to an existing block. Instead it will - overwrite the block content when end is called. If you need to combine block - contents you should fetch the block content when calling start a second time, - or use the capturing mode of ``append()``. -- ``View::prepend()`` no longer has a capturing mode. -- ``View::startIfEmpty()`` has been removed. Now that start() always overwrites - startIfEmpty serves no purpose. -- The ``View::$Helpers`` property has been removed and replaced with - ``_helpers``. If you need to load helpers at runtime you should use - ``$this->addHelper()`` in your view files. -- ``View`` will now raise ``Cake\View\Exception\MissingTemplateException`` when - templates are missing instead of ``MissingViewException``. - -ViewBlock ---------- - -- ``ViewBlock::append()`` has been removed, use :php:meth:`Cake\\View\ViewBlock::concat()` instead. However, - ``View::append()`` still exists. - -JsonView --------- - -- By default JSON data will have HTML entities encoded now. This prevents - possible XSS issues when JSON view content is embedded in HTML files. -- :php:class:`Cake\\View\\JsonView` now supports the ``_jsonOptions`` view - variable. This allows you to configure the bit-mask options used when generating - JSON. - -XmlView -------- - -- :php:class:`Cake\\View\\XmlView` now supports the ``_xmlOptions`` view - variable. This allows you to configure the options used when generating - XML. - -View\\Helper -============ - -- The ``$settings`` property is now called ``$_config`` and should be accessed - through the ``config()`` method. -- Configuration options are no longer set as public properties. -- ``Helper::clean()`` was removed. It was never robust enough - to fully prevent XSS. instead you should escape content with :php:func:`h` or - use a dedicated library like htmlPurifier. -- ``Helper::output()`` was removed. This method was - deprecated in 2.x. -- Methods ``Helper::webroot()``, ``Helper::url()``, ``Helper::assetUrl()``, - ``Helper::assetTimestamp()`` have been moved to new :php:class:`Cake\\View\\Helper\\UrlHelper` - helper. ``Helper::url()`` is now available as :php:meth:`Cake\\View\\Helper\\UrlHelper::build()`. -- Magic accessors to deprecated properties have been removed. The following - properties now need to be accessed from the request object: - - - base - - here - - webroot - - data - - action - - params - -Helper ------- - -Helper has had the following methods removed: - -* ``Helper::setEntity()`` -* ``Helper::entity()`` -* ``Helper::model()`` -* ``Helper::field()`` -* ``Helper::value()`` -* ``Helper::_name()`` -* ``Helper::_initInputField()`` -* ``Helper::_selectedArray()`` - -These methods were part used only by FormHelper, and part of the persistent -field features that have proven to be problematic over time. FormHelper no -longer relies on these methods and the complexity they provide is not necessary -anymore. - -The following methods have been removed: - -* ``Helper::_parseAttributes()`` -* ``Helper::_formatAttribute()`` - -These methods can now be found on the ``StringTemplate`` class that helpers -frequently use. See the ``StringTemplateTrait`` for an easy way to integrate -string templates into your own helpers. - -FormHelper ----------- - -FormHelper has been entirely rewritten for 3.0. It features a few large changes: - -* FormHelper works with the new ORM. But has an extensible system for - integrating with other ORMs or datasources. -* FormHelper features an extensible widget system that allows you to create new - custom input widgets and augment the built-in ones. -* String templates are the foundation of the helper. Instead of munging arrays - together everywhere, most of the HTML FormHelper generates can be customized - in one central place using template sets. - -In addition to these larger changes, some smaller breaking changes have been -made as well. These changes should help streamline the HTML FormHelper generates -and reduce the problems people had in the past: - -- The ``data[`` prefix was removed from all generated inputs. The prefix serves no real purpose anymore. -- The various standalone input methods like ``text()``, ``select()`` and others - no longer generate id attributes. -- The ``inputDefaults`` option has been removed from ``create()``. -- Options ``default`` and ``onsubmit`` of ``create()`` have been removed. Instead - one should use JavaScript event binding or set all required js code for ``onsubmit``. -- ``end()`` can no longer make buttons. You should create buttons with - ``button()`` or ``submit()``. -- ``FormHelper::tagIsInvalid()`` has been removed. Use ``isFieldError()`` - instead. -- ``FormHelper::inputDefaults()`` has been removed. You can use ``templates()`` - to define/augment the templates FormHelper uses. -- The ``wrap`` and ``class`` options have been removed from the ``error()`` - method. -- The ``showParents`` option has been removed from select(). -- The ``div``, ``before``, ``after``, ``between`` and ``errorMessage`` options - have been removed from ``input()``. You can use templates to update the - wrapping HTML. The ``templates`` option allows you to override the loaded - templates for one input. -- The ``separator``, ``between``, and ``legend`` options have been removed from - ``radio()``. You can use templates to change the wrapping HTML now. -- The ``format24Hours`` parameter has been removed from ``hour()``. - It has been replaced with the ``format`` option. -- The ``minYear``, and ``maxYear`` parameters have been removed from ``year()``. - Both of these parameters can now be provided as options. -- The ``dateFormat`` and ``timeFormat`` parameters have been removed from - ``datetime()``. You can use the template to define the order the inputs should - be displayed in. -- The ``submit()`` has had the ``div``, ``before`` and ``after`` options - removed. You can customize the ``submitContainer`` template to modify this - content. -- The ``inputs()`` method no longer accepts ``legend`` and ``fieldset`` in the - ``$fields`` parameter, you must use the ``$options`` parameter. - It now also requires ``$fields`` parameter to be an array. The ``$blacklist`` - parameter has been removed, the functionality has been replaced by specifying - ``'field' => false`` in the ``$fields`` parameter. -- The ``inline`` parameter has been removed from postLink() method. - You should use the ``block`` option instead. Setting ``block => true`` will - emulate the previous behavior. -- The ``timeFormat`` parameter for ``hour()``, ``time()`` and ``dateTime()`` now - defaults to 24, complying with ISO 8601. -- The ``$confirmMessage`` argument of :php:meth:`Cake\\View\\Helper\\FormHelper::postLink()` - has been removed. You should now use key ``confirm`` in ``$options`` to specify - the message. -- Checkbox and radio input types are now rendered *inside* of label elements - by default. This helps increase compatibility with popular CSS libraries like - `Bootstrap `_ and - `Foundation `_. -- Templates tags are now all camelBacked. Pre-3.0 tags ``formstart``, ``formend``, ``hiddenblock`` - and ``inputsubmit`` are now ``formStart``, ``formEnd``, ``hiddenBlock`` and ``inputSubmit``. - Make sure you change them if they are customized in your app. - -It is recommended that you review the :doc:`/views/helpers/form` -documentation for more details on how to use the FormHelper in 3.0. - -HtmlHelper ----------- - -- ``HtmlHelper::useTag()`` has been removed, use ``tag()`` instead. -- ``HtmlHelper::loadConfig()`` has been removed. Customizing the tags can now be - done using ``templates()`` or the ``templates`` setting. -- The second parameter ``$options`` for ``HtmlHelper::css()`` now always requires an array as documented. -- The first parameter ``$data`` for ``HtmlHelper::style()`` now always requires an array as documented. -- The ``inline`` parameter has been removed from meta(), css(), script(), scriptBlock() - methods. You should use the ``block`` option instead. Setting ``block => - true`` will emulate the previous behavior. -- ``HtmlHelper::meta()`` now requires ``$type`` to be a string. Additional options can - further on be passed as ``$options``. -- ``HtmlHelper::nestedList()`` now requires ``$options`` to be an array. The forth argument for the tag type - has been removed and included in the ``$options`` array. -- The ``$confirmMessage`` argument of :php:meth:`Cake\\View\\Helper\\HtmlHelper::link()` - has been removed. You should now use key ``confirm`` in ``$options`` to specify - the message. - -PaginatorHelper ---------------- - -- ``link()`` has been removed. It was no longer used by the helper internally. - It had low usage in user land code, and no longer fit the goals of the helper. -- ``next()`` no longer has 'class', or 'tag' options. It no longer has disabled - arguments. Instead templates are used. -- ``prev()`` no longer has 'class', or 'tag' options. It no longer has disabled - arguments. Instead templates are used. -- ``first()`` no longer has 'after', 'ellipsis', 'separator', 'class', or 'tag' options. -- ``last()`` no longer has 'after', 'ellipsis', 'separator', 'class', or 'tag' options. -- ``numbers()`` no longer has 'separator', 'tag', 'currentTag', 'currentClass', - 'class', 'tag', 'ellipsis' options. These options are now facilitated through - templates. It also requires the ``$options`` parameter to be an array now. -- The ``%page%`` style placeholders have been removed from :php:meth:`Cake\\View\\Helper\\PaginatorHelper::counter()`. - Use ``{{page}}`` style placeholders instead. -- ``url()`` has been renamed to ``generateUrl()`` to avoid method declaration clashes with ``Helper::url()``. - -By default all links and inactive texts are wrapped in ``
  • `` elements. This -helps make CSS easier to write, and improves compatibility with popular CSS -frameworks. - -Instead of the various options in each method, you should use the templates -feature. See the :ref:`paginator-templates` documentation for -information on how to use templates. - -TimeHelper ----------- - -- ``TimeHelper::__set()``, ``TimeHelper::__get()``, and ``TimeHelper::__isset()`` were - removed. These were magic methods for deprecated attributes. -- ``TimeHelper::serverOffset()`` has been removed. It promoted incorrect time math practices. -- ``TimeHelper::niceShort()`` has been removed. - -NumberHelper ------------- - -- :php:meth:`NumberHelper::format()` now requires ``$options`` to be an array. - -SessionHelper -------------- - -- The ``SessionHelper`` has been deprecated. You can use ``$this->request->session()`` directly, - and the flash message functionality has been moved into :doc:`/views/helpers/flash` instead. - -JsHelper --------- - -- ``JsHelper`` and all associated engines have been removed. It could only - generate a very small subset of JavaScript code for selected library and - hence trying to generate all JavaScript code using just the helper often - became an impediment. It's now recommended to directly use JavaScript library - of your choice. - -CacheHelper Removed -------------------- - -CacheHelper has been removed. The caching functionality it provided was -non-standard, limited and incompatible with non-HTML layouts and data views. -These limitations meant a full rebuild would be necessary. Edge Side Includes -have become a standardized way to implement the functionality CacheHelper used -to provide. However, implementing `Edge Side Includes -`_ in PHP has a number of -limitations and edge cases. Instead of building a sub-par solution, we recommend -that developers needing full response caching use `Varnish -`_ or `Squid `_ instead. - -I18n -==== - -The I18n subsystem was completely rewritten. In general, you can expect the same -behavior as in previous versions, specifically if you are using the ``__()`` -family of functions. - -Internally, the ``I18n`` class uses ``Aura\Intl``, and appropriate methods are -exposed to access the specific features of this library. For this reason most -methods inside ``I18n`` were removed or renamed. - -Due to the use of ``ext/intl``, the L10n class was completely removed. It -provided outdated and incomplete data in comparison to the data available from -the ``Locale`` class in PHP. - -The default application language will no longer be changed automatically by the -browser accepted language nor by having the ``Config.language`` value set in the -browser session. You can, however, use a dispatcher filter to get automatic -language switching from the ``Accept-Language`` header sent by the browser:: - - // In config/bootstrap.php - DispatcherFactory::addFilter('LocaleSelector'); - -There is no built-in replacement for automatically selecting the language by -setting a value in the user session. - -The default formatting function for translated messages is no longer -``sprintf``, but the more advanced and feature rich ``MessageFormatter`` class. -In general you can rewrite placeholders in messages as follows:: - - // Before: - __('Today is a %s day in %s', 'Sunny', 'Spain'); - - // After: - __('Today is a {0} day in {1}', 'Sunny', 'Spain'); - -You can avoid rewriting your messages by using the old ``sprintf`` formatter:: - - I18n::defaultFormatter('sprintf'); - -Additionally, the ``Config.language`` value was removed and it can no longer be -used to control the current language of the application. Instead, you can use -the ``I18n`` class:: - - // Before - Configure::write('Config.language', 'fr_FR'); - - // Now - I18n::setLocale('en_US'); - -- The methods below have been moved: - - - From ``Cake\I18n\Multibyte::utf8()`` to ``Cake\Utility\Text::utf8()`` - - From ``Cake\I18n\Multibyte::ascii()`` to ``Cake\Utility\Text::ascii()`` - - From ``Cake\I18n\Multibyte::checkMultibyte()`` to ``Cake\Utility\Text::isMultibyte()`` - -- Since CakePHP now requires the mbstring extension, the - ``Multibyte`` class has been removed. -- Error messages throughout CakePHP are no longer passed through I18n - functions. This was done to simplify the internals of CakePHP and reduce - overhead. The developer facing messages are rarely, if ever, actually translated - - so the additional overhead reaps very little benefit. - -L10n -==== - -- :php:class:`Cake\\I18n\\L10n` 's constructor now takes a :php:class:`Cake\\Network\\Request` instance as argument. - -Testing -======= - -- The ``TestShell`` has been removed. CakePHP, the application skeleton and - newly baked plugins all use ``phpunit`` to run tests. -- The webrunner (webroot/test.php) has been removed. CLI adoption has greatly - increased since the initial release of 2.x. Additionaly, CLI runners offer - superior integration with IDE's and other automated tooling. - - If you find yourself in need of a way to run tests from a browser you should - checkout `VisualPHPUnit `_. It - offers many additional features over the old webrunner. -- ``ControllerTestCase`` is deprecated and will be removed for CakePHP 3.0.0. - You should use the new :ref:`integration-testing` features instead. -- Fixtures should now be referenced using their plural form:: - - // Instead of - $fixtures = ['app.article']; - - // You should use - $fixtures = ['app.articles']; - -Utility -======= - -Set Class Removed ------------------ - -The Set class has been removed, you should use the Hash class instead now. - -Folder & File -------------- - -The folder and file classes have been renamed: - -- ``Cake\Utility\File`` renamed to :php:class:`Cake\\Filesystem\\File` -- ``Cake\Utility\Folder`` renamed to :php:class:`Cake\\Filesystem\\Folder` - -Inflector ---------- - -- The default value for ``$replacement`` argument of :php:meth:`Cake\\Utility\\Inflector::slug()` - has been changed from underscore (``_``) to dash (``-``). Using dashes to - separate words in URLs is the popular choice and also recommended by Google. - -- Transliterations for :php:meth:`Cake\\Utility\\Inflector::slug()` have changed. - If you use custom transliterations you will need to update your code. Instead - of regular expressions, transliterations use simple string replacement. This - yielded significant performance improvements:: - - // Instead of - Inflector::rules('transliteration', [ - '/ä|æ/' => 'ae', - '/å/' => 'aa' - ]); - - // You should use - Inflector::rules('transliteration', [ - 'ä' => 'ae', - 'æ' => 'ae', - 'å' => 'aa' - ]); - -- Separate set of uninflected and irregular rules for pluralization and - singularization have been removed. Instead we now have a common list for each. - When using :php:meth:`Cake\\Utility\\Inflector::rules()` with type 'singular' - and 'plural' you can no longer use keys like 'uninflected', 'irregular' in - ``$rules`` argument array. - - You can add / overwrite the list of uninflected and irregular rules using - :php:meth:`Cake\\Utility\\Inflector::rules()` by using values 'uninflected' and - 'irregular' for ``$type`` argument. - -Sanitize --------- - -- ``Sanitize`` class has been removed. - -Security --------- - -- ``Security::cipher()`` has been removed. It is insecure and promoted bad - cryptographic practices. You should use :php:meth:`Security::encrypt()` - instead. -- The Configure value ``Security.cipherSeed`` is no longer required. With the - removal of ``Security::cipher()`` it serves no use. -- Backwards compatibility in :php:meth:`Cake\\Utility\\Security::rijndael()` for values encrypted prior - to CakePHP 2.3.1 has been removed. You should re-encrypt values using - ``Security::encrypt()`` and a recent version of CakePHP 2.x before migrating. -- The ability to generate a blowfish hash has been removed. You can no longer use type - "blowfish" for ``Security::hash()``. One should just use PHP's `password_hash()` - and `password_verify()` to generate and verify blowfish hashes. The compability - library `ircmaxell/password-compat `_ - which is installed along with CakePHP provides these functions for PHP < 5.5. -- OpenSSL is now used over mcrypt when encrypting/decrypting data. This change - provides better performance and future proofs CakePHP against distros dropping - support for mcrypt. -- ``Security::rijndael()`` is deprecated and only available when using mcrypt. - -.. warning:: - - Data encrypted with Security::encrypt() in previous versions is not - compatible with the openssl implementation. You should :ref:`set the - implementation to mcrypt ` when upgrading. - -Time ----- - -- ``CakeTime`` has been renamed to :php:class:`Cake\\I18n\\Time`. -- ``CakeTime::serverOffset()`` has been removed. It promoted incorrect time math practises. -- ``CakeTime::niceShort()`` has been removed. -- ``CakeTime::convert()`` has been removed. -- ``CakeTime::convertSpecifiers()`` has been removed. -- ``CakeTime::dayAsSql()`` has been removed. -- ``CakeTime::daysAsSql()`` has been removed. -- ``CakeTime::fromString()`` has been removed. -- ``CakeTime::gmt()`` has been removed. -- ``CakeTime::toATOM()`` has been renamed to ``toAtomString``. -- ``CakeTime::toRSS()`` has been renamed to ``toRssString``. -- ``CakeTime::toUnix()`` has been renamed to ``toUnixString``. -- ``CakeTime::wasYesterday()`` has been renamed to ``isYesterday`` to match the rest - of the method naming. -- ``CakeTime::format()`` Does not use ``sprintf`` format strings anymore, you can use - ``i18nFormat`` instead. -- :php:meth:`Time::timeAgoInWords()` now requires ``$options`` to be an array. - -Time is not a collection of static methods anymore, it extends ``DateTime`` to -inherit all its methods and adds location aware formatting functions with the -help of the ``intl`` extension. - -In general, expressions looking like this:: - - CakeTime::aMethod($date); - -Can be migrated by rewriting it to:: - - (new Time($date))->aMethod(); - -Number ------- - -The Number library was rewritten to internally use the ``NumberFormatter`` -class. - -- ``CakeNumber`` has been renamed to :php:class:`Cake\\I18n\\Number`. -- :php:meth:`Number::format()` now requires ``$options`` to be an array. -- :php:meth:`Number::addFormat()` was removed. -- ``Number::fromReadableSize()`` has been moved to :php:meth:`Cake\\Utility\\Text::parseFileSize()`. - -Validation ----------- - -- The range for :php:meth:`Validation::range()` now is inclusive if ``$lower`` and - ``$upper`` are provided. -- ``Validation::ssn()`` has been removed. - -Xml ---- - -- :php:meth:`Xml::build()` now requires ``$options`` to be an array. -- ``Xml::build()`` no longer accepts a URL. If you need to create an XML - document from a URL, use :ref:`Http\\Client `. diff --git a/en/appendices/3-1-migration-guide.rst b/en/appendices/3-1-migration-guide.rst deleted file mode 100644 index 862def9816..0000000000 --- a/en/appendices/3-1-migration-guide.rst +++ /dev/null @@ -1,229 +0,0 @@ -3.1 Migration Guide -################### - -CakePHP 3.1 is a fully API compatible upgrade from 3.0. This page outlines -the changes and improvements made in 3.1. - -Routing -======= - -- The default route class has been changed to ``DashedRoute`` in the - ``cakephp/app`` repo. Your current code base is not affected by this, but it is - recommended to use this route class from now on. -- Name prefix options were added to the various route builder methods. See the - :ref:`named-routes` section for more information. - -Console -======= - -- ``Shell::dispatchShell()`` no longer outputs the welcome message from the - dispatched shell. -- The ``breakpoint()`` helper function has been added. This function provides - a snippet of code that can be put into ``eval()`` to trigger an interactive - console. This is very helpful when debugging in test cases, or other CLI - scripts. -- The ``--verbose`` and ``--quiet`` console options now control stdout/stderr - logging output levels. - -Shell Helpers Added -------------------- - -- Console applications can now create helper classes that encapsulate re-usable - blocks of output logic. See the :doc:`/console-and-shells/helpers` section - for more information. - -RoutesShell ------------ - -- RoutesShell has been added and now provides you a simple to use CLI - interface for testing and debugging routes. See the - :doc:`/console-and-shells/routes-shell` section for more information. - -Controller -========== - -- The following Controller properties are now deprecated: - - * layout - * view - replaced with ``template`` - * theme - * autoLayout - * viewPath - replaced with ``templatePath`` - * viewClass - replaced with ``className`` - * layoutPath - - Instead of setting these properties on your controllers, you should set them - on the view using methods with matching names:: - - // In a controller, instead of - $this->layout = 'advanced'; - - // You should use - $this->viewBuilder()->layout('advanced'); - -These methods should be called after you've determined which view class will be -used by a controller/action. - -AuthComponent -------------- - -- New config option ``storage`` has been added. It contains the storage class name that - ``AuthComponent`` uses to store user record. By default ``SessionStorage`` is used. - If using a stateless authenticator you should configure ``AuthComponent`` to - use ``MemoryStorage`` instead. -- New config option ``checkAuthIn`` has been added. It contains the name of the - event for which auth checks should be done. By default ``Controller.startup`` - is used, but you can set it to ``Controller.initialize`` if you want - authentication to be checked before you controller's ``beforeFilter()`` method - is run. -- The options ``scope`` and ``contain`` for authenticator classes have been - deprecated. Instead, use the new ``finder`` option to configure a custom finder - method and modify the query used to find a user there. -- The logic for setting ``Auth.redirect`` session variable, which is used to get - the URL to be redirected to after login, has been changed. It is now set only when - trying to access a protected URL without authentication. So ``Auth::redirectUrl()`` - returns the protected URL after login. Under normal circumstances, when a user - directly accesses the login page, ``Auth::redirectUrl()`` returns the value set - for ``loginRedirect`` config. - -FlashComponent --------------- - -- ``FlashComponent`` now stacks Flash messages when set with the ``set()`` - or ``__call()`` method. This means that the structure in the Session for - stored Flash messages has changed. - -CsrfComponent -------------- - -- CSRF cookie expiry time can now be set as a ``strtotime()`` compatible value. -- Invalid CSRF tokens will now throw - a ``Cake\Network\Exception\InvalidCsrfTokenException`` instead of the - ``Cake\Network\Exception\ForbiddenException``. - -RequestHandlerComponent ------------------------ - -- ``RequestHandlerComponent`` now switches the layout and template based on - the parsed extension or ``Accept`` header in the ``beforeRender()`` callback - instead of ``startup()``. -- ``addInputType()`` and ``viewClassMap()`` are deprecated. You should use - ``config()`` to modify this configuration data at runtime. -- When ``inputTypeMap`` or ``viewClassMap`` are defined in the component - settings, they will *overwrite* the default values. This change makes it - possible to remove the default configuration. - -Network -======= - -Http\Client ------------ - -- The default mime type used when sending requests has changed. Previously - ``multipart/form-data`` would always be used. In 3.1, ``multipart/form-data`` - is only used when file uploads are present. When there are no file uploads, - ``application/x-www-form-urlencoded`` is used instead. - -ORM -=== - -You can now :ref:`Lazily Eager Load Associations -`. This feature allows you to conditionally -load additional associations into a result set, entity or collection of -entities. - -The ``patchEntity()`` and ``newEntity()`` method now support the ``onlyIds`` -option. This option allows you to restrict hasMany/belongsToMany association -marshalling to only use the ``_ids`` list. This option defaults to ``false``. - -Query ------ - -- ``Query::notMatching()`` was added. -- ``Query::leftJoinWith()`` was added. -- ``Query::innerJoinWith()`` was added. -- ``Query::select()`` now supports ``Table`` and ``Association`` objects as - parameters. These parameter types will select all the columns on the provided - table or association instance's target table. -- ``Query::distinct()`` now accepts a string to distinct on a single column. -- ``Table::loadInto()`` was added. -- ``EXTRACT``, ``DATE_ADD`` and ``DAYOFWEEK`` raw SQL functions have been - abstracted to ``extract()``, ``dateAdd()`` and ``dayOfWeek()``. - -View -==== - -- You can now set ``_serialized`` to ``true`` for ``JsonView`` and ``XmlView`` - to serialize all view variables instead of explicitly specifying them. -- ``View::$viewPath`` is deprecated. You should use ``View::templatePath()`` - instead. -- ``View::$view`` is deprecated. You should use ``View::template()`` - instead. -- ``View::TYPE_VIEW`` is deprecated. You should use ``View::TYPE_TEMPLATE`` - instead. - -Helper -====== - -SessionHelper -------------- - -- The ``SessionHelper`` has been deprecated. You can use - ``$this->request->session()`` directly. - -FlashHelper ------------ - -- ``FlashHelper`` can render multiple messages if multiple messages where - set with the ``FlashComponent``. Each message will be rendered in its own - element. Messages will be rendered in the order they were set. - -FormHelper ----------- - -- New option ``templateVars`` has been added. ``templateVars`` allows you to - pass additional variables to your custom form control templates. - -Email -===== - -- ``Email`` and ``Transport`` classes have been moved under the ``Cake\Mailer`` - namespace. Their former namespaces are still usable as class aliases have - been set for them. -- The ``default`` email profile is now automatically set when an ``Email`` - instance is created. This behavior is similar to what is done in 2.x. - -Mailer ------- - -- The ``Mailer`` class was added. This class helps create reusable emails in an - application. - -I18n -==== - -Time ----- - -- ``Time::fromNow()`` has been added. This method makes it easier to calculate - differences from 'now'. -- ``Time::i18nFormat()`` now supports non-gregorian calendars when formatting - dates. - -Validation -========== - -- ``Validation::geoCoordinate()`` was added. -- ``Validation::latitude()`` was added. -- ``Validation::longitude()`` was added. -- ``Validation::isInteger()`` was added. -- ``Validation::ascii()`` was added. -- ``Validation::utf8()`` was added. - -Testing -======= - -TestFixture ------------ - -``model`` key is now supported to retrieve the table name for importing. diff --git a/en/appendices/3-2-migration-guide.rst b/en/appendices/3-2-migration-guide.rst deleted file mode 100644 index 1ae2fd1cd6..0000000000 --- a/en/appendices/3-2-migration-guide.rst +++ /dev/null @@ -1,166 +0,0 @@ -3.2 Migration Guide -################### - -CakePHP 3.2 is an API compatible upgrade from 3.1. This page outlines the -changes and improvements made in 3.2. - -Minimum PHP 5.5 Required -======================== - -CakePHP 3.2 requires at least PHP 5.5.9. By adopting PHP 5.5 we can provide -better Date and Time libraries and remove dependencies on password compatibility -libraries. - -Deprecations -============ - -As we continue to improve CakePHP, certain features are deprecated as they are -replaced with better solutions. Deprecated features will not be removed until -4.0: - -* ``Shell::error()`` is deprecated because its name does not clearly indicate - that it both outputs a message and stops execution. Use ``Shell::abort()`` - instead. -* ``Cake\Database\Expression\QueryExpression::type()`` is deprecated. Use - ``tieWith()`` instead. -* ``Cake\Database\Type\DateTimeType::$dateTimeClass`` is deprecated. Use - DateTimeType::useMutable() or DateTimeType::useImmutable() instead. -* ``Cake\Database\Type\DateType::$dateTimeClass`` is deprecated. Use - ``DateTimeType::useMutable()`` or ``DateType::useImmutable()`` instead. -* ``Cake\ORM\ResultSet::_calculateTypeMap()`` is now unused and deprecated. -* ``Cake\ORM\ResultSet::_castValues()`` is now unused and deprecated. -* The ``action`` key for ``FormHelper::create()`` has been deprecated. You - should use the ``url`` key directly. - -Disabling Deprecation Warnings ------------------------------- - -Upon upgrading you may encounter several deprecation warnings. These warnings -are emitted by methods, options and functionality that will be removed in -CakePHP 4.x, but will continue to exist throughout the lifetime of 3.x. While we -recommend addressing deprecation issues as they are encountered, that is not -always possible. If you'd like to defer fixing deprecation notices, you can -disable them in your **config/app.php**:: - - 'Error' => [ - 'errorLevel' => E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED, - ] - -The above error level will suppress deprecation warnings from CakePHP. - -New Enhancements -================ - -Carbon Replaced with Chronos ----------------------------- - -The Carbon library has been replaced with :doc:`cakephp/chronos `. -This new library is a fork of Carbon with no additional dependencies. It also -offer a calendar date object, and immutable versions of both date and datetime -objects. - -New Date Object ---------------- - -The ``Date`` class allows you to cleanly map ``DATE`` columns into PHP objects. -Date instances will always fix their time to ``00:00:00 UTC``. By default the -ORM creates instances of ``Date`` when mapping ``DATE`` columns now. - -New Immutable Date and Time Objects ------------------------------------ - -The ``FrozenTime``, and ``FrozenDate`` classes were added. These classes offer -the same API as the ``Time`` object has. The frozen classes provide immutable -variants of ``Time`` and ``Date``. By using immutable objects, you can prevent -accidental mutations. Instead of in-place modifications, modifier methods return -*new* instances:: - - use Cake\I18n\FrozenTime; - - $time = new FrozenTime('2016-01-01 12:23:32'); - $newTime = $time->modify('+1 day'); - -In the above code ``$time`` and ``$newTime`` are different objects. The -``$time`` object retains its original value, while ``$newTime`` has the modified -value. See the :ref:`immutable-time` section for more information. As of 3.2, -the ORM can map date/datetime columns into immutable objects. See the -:ref:`immutable-datetime-mapping` section for more information. - -CorsBuilder Added ------------------ - -In order to make setting headers related to Cross Origin Requests (CORS) easier, -a new ``CorsBuilder`` has been added. This class lets you define CORS related -headers with a fluent interface. See :ref:`cors-headers` for more information. - -RedirectRoute raises an exception on redirect ---------------------------------------------- - -``Router::redirect()`` now raises ``Cake\Network\Routing\RedirectException`` -when a redirect condition is reached. This exception is caught by the routing -filter and converted into a response. This replaces calls to -``response->send()`` and allows dispatcher filters to interact with redirect -responses. - -ORM Improvements ----------------- - -* Containing the same association multiple times now works as expected, and the - query builder functions are now stacked. -* Function expressions now correctly cast their results. This means that - expressions like ``$query->func()->current_date()`` will return datetime - instances. -* Field data that fails validation can now be accessed in entities via the - ``invalid()`` method. -* Entity accessor method lookups are now cached and perform better. - -Improved Validator API ----------------------- - -The Validator object has a number of new methods that make building validators -less verbose. For example adding validation rules to a username field can now -look like:: - - $validator->email('username') - ->ascii('username') - ->lengthBetween('username', [4, 8]); - -Console Improvements --------------------- - -* ``Shell::info()``, ``Shell::warn()`` and ``Shell::success()`` were added. - These helper methods make using commonly used styling simpler. -* ``Cake\Console\Exception\StopException`` was added. -* ``Shell::abort()`` was added to replace ``error()``. - -StopException Added -------------------- - -``Shell::_stop()`` and ``Shell::error()`` no longer call ``exit()``. Instead -they raise ``Cake\Console\Exception\StopException``. If your shells/tasks are -catching ``\Exception`` where these methods would have been called, those catch -blocks will need to be updated so they don't catch the ``StopException``. By not -calling ``exit()`` testing shells should be easier and require fewer mocks. - -Helper initialize() added -------------------------- - -Helpers can now implement an ``initialize(array $config)`` hook method like -other class types. - -Fatal Error Memory Limit Handling ---------------------------------- - -A new configuration option ``Error.extraFatalErrorMemory`` can be set to the -number of megabytes to increase the memory limit by when a fatal error is -encountered. This allows breathing room to complete logging or error handling. - -Migration Steps -=============== - -Updating setToStringFormat() ----------------------------- - -Before CakePHP 3.2 using Time::setToStringFormat() was working on Date Objects -as well. After upgrading you will need to add Date::setToStringFormat() in -addition to see the formatted Date again. diff --git a/en/appendices/3-3-migration-guide.rst b/en/appendices/3-3-migration-guide.rst deleted file mode 100644 index eef50a0177..0000000000 --- a/en/appendices/3-3-migration-guide.rst +++ /dev/null @@ -1,186 +0,0 @@ -3.3 Migration Guide -################### - -CakePHP 3.3 is an API compatible upgrade from 3.2. This page outlines the -changes and improvements made in 3.3. - -Deprecations -============ - -* ``Router::mapResources()`` is deprecated. Use routing scopes and - ``$routes->resources()`` instead. -* ``Router::redirect()`` is deprecated. Use routing scopes and - ``$routes->redirect()`` instead. -* ``Router::parseNamedParams()`` is deprecated. Named parameter backwards - compatibility will be removed in 4.0.0 -* ``Cake\Http\Client\Response`` has had the following methods deprecated because they - overlap with PSR-7 interface methods: - - * ``statusCode()`` use ``getStatusCode()`` instead. - * ``encoding()`` use ``getEncoding()`` instead. - * ``header()`` use ``getHeaderLine()`` instead. - * ``cookie()`` use ``getCookie()`` instead. - * ``version()`` use ``getProtocolVersion()`` instead. -* Dispatcher Filters are now deprecated. Use :doc:`/controllers/middleware` - instead. -* ``RequestActionTrait`` has been deprecated. Refactor your code to use - :doc:`/views/cells` instead. -* ``Cake\\Utility\\Crypto\\Mcrypt`` engine has been deprecated as the ``mcrypt`` - extension is deprecated in PHP 7.1. Use the ``openssl`` and - :php:class:`Cake\\Utility\\Crypto\\Openssl` instead. - -Behavior Changes -================ - -While these changes are API compatible, they represent minor variances in -behavior that may effect your application: - -* The default JSON encode format for Date and DateTime instances is now - ISO-8601. This means that the timezone value contains a ``:``. - For example ``2015-11-06T00:00:00+03:00`` -* ``Controller::referer()`` now consistently omits the application base path - when generating application local URLs. Previously string URLs would have the - base path prepended to them, while array URLs would not. -* The default ``ErrorController`` no longer disables ``Auth`` and ``Security`` - components, as it does not extend ``AppController``. If you are enabling these - components through events, you will need to update your code. -* ``Entity::clean`` now cleans original values, clearing them on save. This - behavior was a bug as the entity's original state should not be retained after - a save, but instead reflect the new state of the entity. - -PSR-7 Middleware Support Added -============================== - -In tandem with the deprecation of Dispatcher Filters, support for PSR-7 -middleware has been added. Middleware is part of the new HTTP stack that is an -opt-in component of CakePHP 3.3.0. By using the new HTTP stack, you can take -advantage of features like: - -* Using middleware from plugins, and libraries outside of CakePHP. -* Leverage the same response object methods in both the responses you get from - ``Http\Client`` and the responses your application generates. -* Be able to augment the response objects emitted by error handling and asset - delivery. - -See the :doc:`/controllers/middleware` chapter and :ref:`adding-http-stack` -sections for more information and how to add the new HTTP stack to an existing -application. - -Http Client is now PSR-7 Compatible -=================================== - -``Cake\Network\Http\Client`` has been moved to ``Cake\Http\Client``. Its request -and response objects now implement the -`PSR-7 interfaces `__. Several methods on -``Cake\Http\Client\Response`` are now deprecated, see above for more -information. - -ORM Improvements -================ - -* Additional support has been added for mapping complex data types. This makes - it easier to work with geo-spatial types, and data that cannot be represented - by strings in SQL queries. See the - :ref:`mapping-custom-datatypes-to-sql-expressions` for more information. -* A new ``JsonType`` was added. This new type lets you use the native JSON types - available in MySQL and Postgres. In other database providers the ``json`` type - will map to ``TEXT`` columns. -* ``Association::unique()`` was added. This method proxies the target table's - ``unique()`` method, but ensures that association conditions are applied. -* ``isUnique`` rules now apply association conditions. -* When entities are converted into JSON, the associated objects are no longer - converted to an array first using ``toArray()``. Instead, the - ``jsonSerialize()`` method will be invoked on all associated entities. This - gives you more flexibility and control on which properties are exposed in JSON - representations of your entities. -* ``Table::newEntity()`` and ``Table::patchEntity()`` will now raise an - exception when an unknown association is in the 'associated' key. -* ``RulesChecker::validCount()`` was added. This new method allows to apply - rules to the number of associated records an entity has. -* The ``allowNullableNulls`` option was added to the ``existsIn`` rule. This - option allows rules to pass when some columns are null. -* Saving translated records is now simpler. See the - :ref:`saving-multiple-translations` for more information. - -Multiple Pagination Support Added -================================= - -You can now paginate multiple queries in a single controller action/view -template. See the :ref:`paginating-multiple-queries` section for more -details. - -Cache Shell Added -================= - -To help you better manage cached data from the CLI environment, a shell command -has been added that exposes methods for clearing cached data:: - - // Clear one cache config - bin/cake cache clear - - // Clear all cache configs - bin/cake cache clear_all - -FormHelper -========== - -* FormHelper will now automatically set the default value of fields to the - default value defined in your database columns. You can disable this behavior - by setting ``schemaDefault`` option to false. - -Validation -========== - -* ``Validator::requirePresence()``, ``Validator::allowEmpty()`` and - ``Validator::notEmpty()`` now accept a list of fields. This allows you - to more concisely define the fields that are required. - -StringTemplate -============== - -``StringTemplate::format()`` now throws an exception instead of returning -``null`` when requested template is not found. - -Other Enhancements -================== - -* ``Collection::transpose()`` was added. This method allows you to tranpose the - rows and columns of a matrix with equal length rows. -* The default ``ErrorController`` now loads ``RequestHandlerComponent`` to - enable ``Accept`` header based content-type negotiation for error pages. - -Routing -------- - -* ``Router::parse()``, ``RouteCollection::parse()`` and ``Route::parse()`` had - a ``$method`` argument added. It defaults to 'GET'. This new parameter reduces - reliance on global state, and necessary for the PSR-7 work integration to be - done. -* When building resource routes, you can now define a prefix. This is useful - when defining nested resources as you can create specialized controllers for - nested resources. -* Dispatcher Filters are now deprecated. Use :doc:`/controllers/middleware` - instead. - -Console -------- - -* Shell tasks that are invoked directly from the CLI no longer have their - ``_welcome`` method invoked. They will also have the ``requested`` parameter - set now. -* ``Shell::err()`` will now apply the 'error' style to text. The default - styling is red text. - -Request -------- - -* ``Request::is()`` and ``Request::addDetector()`` now supports additional - arguments in detectors. This allows detector callables to operate on - additional parameters. - -Debugging Functions -------------------- - -* The ``pr()``, ``debug()``, and ``pj()`` functions now return the value being - dumped. This makes them easier to use when values are being returned. -* :php:func:`dd()` has been added to completely halt execution. diff --git a/en/appendices/3-4-migration-guide.rst b/en/appendices/3-4-migration-guide.rst deleted file mode 100644 index 0f0b00ae8f..0000000000 --- a/en/appendices/3-4-migration-guide.rst +++ /dev/null @@ -1,471 +0,0 @@ -3.4 Migration Guide -################### - -CakePHP 3.4 is an API compatible upgrade from 3.3. This page outlines the -changes and improvements made in 3.4. - -Minimum PHP 5.6 Required -======================== -CakePHP 3.4 requires at least PHP 5.6.0 as PHP 5.5 is no longer supported and -won't receive any security fixes anymore. - -Deprecations -============ - -The following is a list of deprecated methods, properties and behaviors. These -features will continue to function until 4.0.0 after which they will be removed. - -Request & Response Deprecations -------------------------------- - -The bulk of deprecations for 3.4 are in the ``Request`` and ``Response`` -objects. The existing methods that modify objects in-place are now deprecated, -and superseded by methods that follow the immutable object patterns described in -the PSR-7 standard. - -Several properties on ``Cake\Network\Request`` have been deprecated: - -* ``Request::$params`` is deprecated. Use ``Request::getAttribute('params')`` instead. -* ``Request::$data`` is deprecated. Use ``Request::getData()`` instead. -* ``Request::$query`` is deprecated. Use ``Request::getQueryParams()`` instead. -* ``Request::$cookies`` is deprecated. Use ``Request::getCookie()`` instead. -* ``Request::$base`` is deprecated. Use ``Request::getAttribute('base')`` instead. -* ``Request::$webroot`` is deprecated. Use ``Request::getAttribute('webroot')`` instead. -* ``Request::$here`` is deprecated. Use ``Request::getAttribute('here')`` instead. -* ``Request::$_session`` was renamed to ``Request::$session``. - -A number of methods on ``Cake\Network\Request`` have been deprecated: - -* ``__get()`` & ``__isset()`` methods are deprecated. Use ``getParam()`` instead. -* ``method()`` is deprecated. Use ``getMethod()`` instead. -* ``setInput()`` is deprecated. Use ``withBody()`` instead. -* The ``ArrayAccess`` methods have all been deprecated. -* ``Request::param()`` is deprecated. Use ``Request::getParam()`` instead. -* ``Request::data()`` is deprecated. Use ``Request::getData()`` instead. -* ``Request::query()`` is deprecated. Use ``Request::getQuery()`` instead. -* ``Request::cookie()`` is deprecated. Use ``Request::getCookie()`` instead. - -Several methods on ``Cake\Network\Response`` have been deprecated because they -either overlap the PSR-7 methods, or are made obsolete by the PSR-7 stack: - -* ``Response::header()`` is deprecated. Use ``getHeaderLine()``, ``hasHeader()`` or - ``Response::getHeader()`` instead. -* ``Response::body()`` is deprecated. Use ``Response::withBody()`` instead. -* ``Response::statusCode()`` is deprecated. Use ``Response::getStatusCode()`` instead. -* ``Response::httpCodes()`` This method should no longer be used. CakePHP now supports all - standards recommended status codes. -* ``Response::protocol()`` is deprecated. Use ``Response::getProtocolVersion()`` instead. -* ``send()``, ``sendHeaders()``, ``_sendHeader()``, ``_sendContent()``, - ``_setCookies()``, ``_setContentType()``, and ``stop()`` are deprecated and - made obsolete by the PSR-7 HTTP stack. - -With responses heading towards immutable object patterns as recommended by the -PSR-7 standards, a number of 'helper' methods in ``Response`` have been -deprecated and immutable variants are now recommended: - -* ``Response::location()`` would become ``Response::withLocation()`` -* ``Response::disableCache()`` would become ``Response::withDisabledCache()`` -* ``Response::type()`` would become ``Response::withType()`` -* ``Response::charset()`` would become ``Response::withCharset()`` -* ``Response::cache()`` would become ``Response::withCache()`` -* ``Response::modified()`` would become ``Response::withModified()`` -* ``Response::expires()`` would become ``Response::withExpires()`` -* ``Response::sharable()`` would become ``Response::withSharable()`` -* ``Response::maxAge()`` would become ``Response::withMaxAge()`` -* ``Response::vary()`` would become ``Response::withVary()`` -* ``Response::etag()`` would become ``Response::withEtag()`` -* ``Response::compress()`` would become ``Response::withCompression()`` -* ``Response::length()`` would become ``Response::withLength()`` -* ``Response::mustRevalidate()`` would become ``Response::withMustRevalidate()`` -* ``Response::notModified()`` would become ``Response::withNotModified()`` -* ``Response::cookie()`` would become ``Response::withCookie()`` -* ``Response::file()`` would become ``Response::withFile()`` -* ``Response::download()`` would become ``Response::withDownload()`` - -Please see the :ref:`adopting-immutable-responses` section for more information -before updating your code as using responses through the immutable methods will -require additional changes. - -Other Deprecations ------------------- - -* The public properties on ``Cake\Event\Event`` are deprecated, new methods have - been added to read/write the relevant properties. -* ``Event::name()`` is deprecated. Use ``Event::getName()`` instead. -* ``Event::subject()`` is deprecated. Use ``Event::getSubject()`` instead. -* ``Event::result()`` is deprecated. Use ``Event::getResult()`` instead. -* ``Event::data()`` is deprecated. Use ``Event::getData()`` instead. -* The ``Auth.redirect`` session variable is no longer used. Instead a query - string parameter is used to store the redirect URL. This has the additional - effect of removing the ability to store a redirect URL in the session outside - of login scenarios. -* ``AuthComponent`` no longer stores redirect URLs when the unauthorized URL is - not a ``GET`` action. -* The ``ajaxLogin`` option for ``AuthComponent`` is deprecated. You should use the - ``403`` status code to trigger the correct behavior in clientside code now. -* The ``beforeRedirect`` method of ``RequestHandlerComponent`` is now - deprecated. -* The ``306`` status code in ``Cake\Network\Response`` is now deprecated and has - its status phrase changed to 'Unused' as this status code is non-standard. -* ``Cake\Database\Schema\Table`` has been renamed to - ``Cake\Database\Schema\TableSchema``. The previous name was confusing to a number - of users. -* The ``fieldList`` option for ``Cake\ORM\Table::newEntity()`` and - ``patchEntity()`` has been renamed to ``fields`` to be more consistent with - other parts of the ORM. -* ``Router::parse()`` is deprecated. ``Router::parseRequest()`` should be used - instead as it accepts a request and gives more control/flexibility in handling - incoming requests. -* ``Route::parse()`` is deprecated. ``Route::parseRequest()`` should be used - instead as it accepts a request and gives more control/flexibility in handling - incoming requests. -* ``FormHelper::input()`` is deprecated. Use ``FormHelper::control()`` instead. -* ``FormHelper::inputs()`` is deprecated. Use ``FormHelper::controls()`` instead. -* ``FormHelper::allInputs()`` is deprecated. Use ``FormHelper::allControls()`` instead. -* ``Mailer::layout()`` is deprecated. Use ``Mailer::setLayout()`` provided by - ``Mailer::__call()`` instead. - -Deprecated Combined Get/Set Methods ------------------------------------ - -In the past CakePHP has leveraged 'modal' methods that provide both -a get/set mode. These methods complicate IDE autocompletion and our ability -to add stricter return types in the future. For these reasons, combined get/set -methods are being split into separate get and set methods. - -The following is a list of methods that are deprecated and replaced with -``getX()`` and ``setX()`` methods: - -``Cake\Core\InstanceConfigTrait`` - * ``config()`` -``Cake\Core\StaticConfigTrait`` - * ``config()`` - * ``dsnClassMap()`` -``Cake\Console\ConsoleOptionParser`` - * ``command()`` - * ``description()`` - * ``epilog()`` -``Cake\Database\Connection`` - * ``driver()`` - * ``schemaCollection()`` - * ``useSavePoints()`` (now ``enableSavePoints()``/``isSavePointsEnabled()``) -``Cake\Database\Driver`` - * ``autoQuoting`` (now ``enableAutoQuoting()``/``isAutoQuotingEnabled()``) -``Cake\Database\Expression\FunctionExpression`` - * ``name()`` -``Cake\Database\Expression\QueryExpression`` - * ``tieWith()`` (now ``setConjunction()``/``getConjunction()``) -``Cake\Database\Expression\ValuesExpression`` - * ``columns()`` - * ``values()`` - * ``query()`` -``Cake\Database\Query`` - * ``connection()`` - * ``selectTypeMap()`` - * ``bufferResults()`` (now ``enableBufferedResults()``/``isBufferedResultsEnabled()``) -``Cake\Database\Schema\CachedCollection`` - * ``cacheMetadata()`` -``Cake\Database\Schema\TableSchema`` - * ``options()`` - * ``temporary()`` (now ``setTemporary()``/``isTemporary()``) -``Cake\Database\TypeMap`` - * ``defaults()`` - * ``types()`` -``Cake\Database\TypeMapTrait`` - * ``typeMap()`` - * ``defaultTypes()`` -``Cake\ORM\Association`` - * ``name()`` - * ``cascadeCallbacks()`` - * ``source()`` - * ``target()`` - * ``conditions()`` - * ``bindingKey()`` - * ``foreignKey()`` - * ``dependent()`` - * ``joinType()`` - * ``property()`` - * ``strategy()`` - * ``finder()`` -``Cake\ORM\Association\BelongsToMany`` - * ``targetForeignKey()`` - * ``saveStrategy()`` - * ``conditions()`` -``Cake\ORM\Association\HasMany`` - * ``saveStrategy()`` - * ``foreignKey()`` - * ``sort()`` -``Cake\ORM\Association\HasOne`` - * ``foreignKey()`` -``Cake\ORM\EagerLoadable`` - * ``config()`` - * setter part of ``canBeJoined()`` (now ``setCanBeJoined()``) -``Cake\ORM\EagerLoader`` - * ``matching()`` (``getMatching()`` will have to be called after ``setMatching()`` - to keep the old behavior) - * ``autoFields()`` (now ``enableAutoFields()``/``isAutoFieldsEnabled()``) -``Cake\ORM\Locator\TableLocator`` - * ``config()`` -``Cake\ORM\Query`` - * ``eagerLoader()`` - * ``hydrate()`` (now ``enableHydration()``/``isHydrationEnabled()``) - * ``autoFields()`` (now ``enableAutoFields()``/``isAutoFieldsEnabled()``) -``Cake\ORM\Table`` - * ``table()`` - * ``alias()`` - * ``registryAlias()`` - * ``connection()`` - * ``schema()`` - * ``primaryKey()`` - * ``displayField()`` - * ``entityClass()`` -``Cake\Mailer\Email`` - * ``from()`` - * ``sender()`` - * ``replyTo()`` - * ``readReceipt()`` - * ``returnPath()`` - * ``to()`` - * ``cc()`` - * ``bcc()`` - * ``charset()`` - * ``headerCharset()`` - * ``emailPattern()`` - * ``subject()`` - * ``template()`` (now ``setTemplate()``/``getTemplate()`` and ``setLayout()``/``getLayout()``) - * ``viewRender()`` (now ``setViewRenderer()``/``getViewRenderer()``) - * ``viewVars()`` - * ``theme()`` - * ``helpers()`` - * ``emailFormat()`` - * ``transport()`` - * ``messageId()`` - * ``domain()`` - * ``attachments()`` - * ``configTransport()`` - * ``profile()`` -``Cake\Validation\Validator`` - * ``provider()`` -``Cake\View\StringTemplateTrait`` - * ``templates()`` -``Cake\View\ViewBuilder`` - * ``templatePath()`` - * ``layoutPath()`` - * ``plugin()`` - * ``helpers()`` - * ``theme()`` - * ``template()`` - * ``layout()`` - * ``options()`` - * ``name()`` - * ``className()`` - * ``autoLayout()`` (now ``enableAutoLayout()``/``isAutoLayoutEnabled()``) - -.. _adopting-immutable-responses: - -Adopting Immutable Responses -============================ - -Before you migrate your code to use the new response methods you should be aware -of the conceptual differences the new methods have. The immutable methods are -generally indicated using a ``with`` prefix. For example, ``withLocation()``. -Because these methods operate in an immutable context, they return *new* -instances which you need to assign to variables or properties. If you had -controller code that looked like:: - - $response = $this->response; - $response->location('/login') - $response->header('X-something', 'a value'); - -If you were to simply find & replace method names your code would break. Instead -you must now use code that looks like:: - - $this->response = $this->response - ->withLocation('/login') - ->withHeader('X-something', 'a value'); - -There are a few key differences: - -#. The result of your changes is re-assigned to ``$this->response``. This is - critical to preserving the intent of the above code. -#. The setter methods can all be chained together. This allows you to skip - storing all the intermediate objects. - -Component Migration Tips ------------------------- - -In previous versions of CakePHP, Components often held onto references to both -the request and response, in order to make changes later. Before you adopt the -immutable methods you should use the response attached to the Controller:: - - // In a component method (not a callback) - $this->response->header('X-Rate-Limit', $this->remaining); - - // Should become - $controller = $this->getController(); - $controller->response = $controller->response->withHeader('X-Rate-Limit', $this->remaining); - -In component callbacks you can use the event object to access the -response/controller:: - - public function beforeRender($event) - { - $controller = $event->getSubject(); - $controller->response = $controller->response->withHeader('X-Teapot', 1); - } - -.. tip:: - Instead of holding onto references of Responses, always get the current - response from the controller, and re-assign the response property when you - are done. - -Behavior Changes -================ - -While these changes are API compatible, they represent minor variances in -behavior that may affect your application: - -* ``ORM\Query`` results will not typecast aliased columns based on the original - column's type. For example if you alias ``created`` to ``created_time`` you - will now get a ``Time`` object back instead of a string. -* Internal ORM traits used to build Association classes have been removed and - replaced with new internal APIs. This shouldn't impact your applications, but - may if you have created custom association types. -* ``AuthComponent`` now uses a query string to store the redirect URL when an - unauthenticated user is redirected to the login page. Previously, this redirect - was stored in the session. Using the query string allows for better - multi-browser experience. -* Database Schema reflection now treats unknown column types as ``string`` and - not ``text``. A visible impact of this is that ``FormHelper`` will generate - text inputs instead of textarea elements for unknown column types. -* ``AuthComponent`` no longer stores the flash messages it creates under the - 'auth' key. They are now rendered with the 'error' template under the - 'default' flash message key. This simplifies using ``AuthComponent``. -* ``Mailer\Email`` will now autodetect attachment content types using - ``mime_content_type`` if a content-type is not provided. Previously - attachments would have defaulted to 'application/octet-stream'. -* CakePHP now uses the ``...`` operator in place of ``call_user_func_array()``. - If you are passing associative arrays, you - should update your code to pass a numerically indexed array using - ``array_values()`` for the following methods: - - * ``Cake\Mailer\Mailer::send()`` - * ``Cake\Controller\Controller::setAction()`` - * ``Cake\Http\ServerRequest::is()`` - -Visibility Changes -================== - -* ``MailerAwareTrait::getMailer()`` will now become protected. -* ``CellTrait::cell()`` will now become protected. - -If the above traits are used in controllers, their public methods could be -accessed by default routing as actions. These changes help protect your -controllers. If you need the methods to remain public you will need to update -your ``use`` statement to look like:: - - use CellTrait { - cell as public; - } - use MailerAwareTrait { - getMailer as public; - } - -Collection -========== - -* ``CollectionInterface::chunkWithKeys()`` was added. User land implementations - of the ``CollectionInterface`` will need to implement this method now. -* ``Collection::chunkWithKeys()`` was added. - -Error -===== - -* ``Debugger::setOutputMask()`` and ``Debugger::outputMask()`` were added. These - methods allow you to configure properties/array keys that should be masked - from output generated by Debugger (for instance, when calling ``debug()``). - -Event -===== - -* ``Event::getName()`` was added. -* ``Event::getSubject()`` was added. -* ``Event::getData()`` was added. -* ``Event::setData()`` was added. -* ``Event::getResult()`` was added. -* ``Event::setResult()`` was added. - -I18n -==== - -* You can now customize the behavior of the fallback message loader. See - :ref:`creating-generic-translators` for more information. - -Routing -======= - -* ``RouteBuilder::prefix()`` now accepts an array of defaults to add to each - connected route. -* Routes can now match only specific hosts through the ``_host`` option. - -Email -===== - -* ``Email::setPriority()``/``Email::getPriority()`` have been added. - -HtmlHelper -========== - -* ``HtmlHelper::scriptBlock()`` no longer wraps the JavaScript code in ``` on a per-engine basis. -* ``Cake\Database\Type\DateTimeType`` will now marshal ISO-8859-1 formatted - datetime strings (e.g. 2017-07-09T12:33:00+00:02) in addition to the - previously accepted format. If you have a subclass of DateTimeType you may - need to update your code. - -New Features -============ - -Scoped Middleware ------------------ - -Middleware can now be conditionally applied to routes in specific URL -scopes. This allows you to build specific stacks of middleware for different -parts of your application without having to write URL checking code in your -middleware. See the :ref:`connecting-scoped-middleware` section for more -information. - -New Console Runner ------------------- - -3.5.0 adds ``Cake\Console\CommandRunner``. This class alongside -``Cake\Console\CommandCollection`` integrate the CLI environment with the new -``Application`` class. Application classes can now implement a ``console()`` -hook that allows them to have full control over which CLI commands are exposed, -how they are named and how the shells get their dependencies. Adopting this new -class requires replacing the contents of your ``bin/cake.php`` file with the -`following file `_. - -Cache Engine Fallbacks ----------------------- - -Cache engines can now be configured with a ``fallback`` key that defines a -cache configuration to fall back to if the engine is misconfigured (or -unavailable). See :ref:`cache-configuration-fallback` for more information on -configuring fallbacks. - -dotenv Support added to Application Skeleton --------------------------------------------- - -The application skeleton now features a 'dotenv' integration making it easier to -use environment variables to configure your application. See the -:ref:`environment-variables` section for more information. - -Console Integration Testing ---------------------------- - -The ``Cake\TestSuite\ConsoleIntegrationTestCase`` class was added to make -integration testing console applications easier. For more information, visit -the :ref:`console-integration-testing` section. This test class is fully -compatible with the current ``Cake\Console\ShellDispatcher`` as well as the new -``Cake\Console\CommandRunner``. - -Collection ----------- - -* ``Cake\Collection\Collection::avg()`` was added. -* ``Cake\Collection\Collection::median()`` was added. - -Core ----- - -* ``Cake\Core\Configure::read()`` now supports default values if the desired key - does not exist. -* ``Cake\Core\ObjectRegistry`` now implements the ``Countable`` and - ``IteratorAggregate`` interfaces. - -Console -------- - -* ``Cake\Console\ConsoleOptionParser::setHelpAlias()`` was added. This method - allows you to set the command name used when generating help output. Defaults - to ``cake``. -* ``Cake\Console\CommandRunnner`` was added replacing - ``Cake\Console\ShellDispatcher``. -* ``Cake\Console\CommandCollection`` was added to provide an interface for - applications to define the command line tools they offer. - -Database --------- - -* SQLite driver had the ``mask`` option added. This option lets you set the - file permissions on the SQLite database file when it is created. - -Datasource ----------- - -* ``Cake\Datasource\SchemaInterface`` was added. -* New abstract types were added for ``smallinteger`` and ``tinyinteger``. - Existing ``SMALLINT`` and ``TINYINT`` columns will now be reflected as these - new abstract types. ``TINYINT(1)`` columns will continue to be treated as - boolean columns in MySQL. -* ``Cake\Datasource\PaginatorInterface`` was added. The ``PaginatorComponent`` - now uses this interface to interact with paginators. This allows other - ORM-like implementations to be paginated by the component. -* ``Cake\Datasource\Paginator`` was added to paginate ORM/Database Query - instances. - -Event ------ - -* ``Cake\Event\EventManager::on()`` and ``off()`` methods are now chainable - making it simpler to set multiple events at once. - -Http ----- - -* New ``Cookie`` & ``CookieCollection`` classes have been added. These classes allow you - to work with cookies in an object-orientated way, and are available on - ``Cake\Http\ServerRequest``, ``Cake\Http\Response``, and - ``Cake\Http\Client\Response``. See the :ref:`request-cookies` and - :ref:`response-cookies` for more information. -* New middleware has been added to make applying security headers easier. See - :ref:`security-header-middleware` for more information. -* New middleware has been added to transparently encrypt cookie data. See - :ref:`encrypted-cookie-middleware` for more information. -* New middleware has been added to make protecting against CSRF easier. See - :ref:`csrf-middleware` for more information. -* ``Cake\Http\Client::addCookie()`` was added to make it easy to add cookies to - a client instance. - -InstanceConfigTrait -------------------- - -* ``InstanceConfigTrait::getConfig()`` now takes a 2nd parameter ``$default``. - If no value is available for the specified ``$key``, the ``$default`` value - will be returned. - -ORM ---- - -* ``Cake\ORM\Query::contain()`` now allows you to call it without the wrapping - array when containing a single association. ``contain('Comments', function () - { ... });`` will now work. This makes ``contain()`` consistent with other - eagerloading related methods like ``leftJoinWith()`` and ``matching()``. - -Routing -------- - -* ``Cake\Routing\Router::reverseToArray()`` was added. This method allow you to - convert a request object into an array that can be used to generate URL - strings. -* ``Cake\Routing\RouteBuilder::resources()`` had the ``path`` option - added. This option lets you make the resource path and controller name not - match. -* ``Cake\Routing\RouteBuilder`` now has methods to create routes for - specific HTTP methods. e.g ``get()`` and ``post()``. -* ``Cake\Routing\RouteBuilder::loadPlugin()`` was added. -* ``Cake\Routing\Route`` now has fluent methods for defining options. - -TestSuite ---------- - -* ``TestCase::loadFixtures()`` will now load all fixtures when no arguments are - provided. -* ``IntegrationTestCase::head()`` was added. -* ``IntegrationTestCase::options()`` was added. -* ``IntegrationTestCase::disableErrorHandlerMiddleware()`` was added to make - debugging errors easier in integration tests. - -Validation ----------- - -* ``Cake\Validation\Validator::scalar()`` was added to ensure that fields do not - get non-scalar data. -* ``Cake\Validation\Validator::regex()`` was added for a more convenient way - to validate data against a regex pattern. -* ``Cake\Validation\Validator::addDefaultProvider()`` was added. This method - lets you inject validation providers into all the validators created in your - application. -* ``Cake\Validation\ValidatorAwareInterface`` was added to define the methods - implemented by ``Cake\Validation\ValidatorAwareTrait``. - -View ----- - -* ``Cake\View\Helper\PaginatorHelper::limitControl()`` was added. This method - lets you create a form with a select box for updating the limit value on - a paginated result set. diff --git a/en/appendices/3-6-migration-guide.rst b/en/appendices/3-6-migration-guide.rst deleted file mode 100644 index adfa95679b..0000000000 --- a/en/appendices/3-6-migration-guide.rst +++ /dev/null @@ -1,326 +0,0 @@ -3.6 Migration Guide -################### - -CakePHP 3.6 is an API compatible upgrade from 3.5. This page outlines the -changes and improvements made in 3.6. - -To upgrade to 3.6.x run the following composer command: - -.. code-block:: bash - - php composer.phar require --update-with-dependencies "cakephp/cakephp:3.6.*" - -Deprecations -============ - -The following is a list of deprecated methods, properties and behaviors. These -features will continue to function until 4.0.0 after which they will be removed. - -* ``bin/cake orm_cache`` is now ``bin/cake schema_cache``. -* ``Cake\Cache\Engine\ApcEngine`` has been renamed to - ``Cake\Cache\Engine\ApcuEngine`` to better reflect the extension name. -* ``Cake\ORM\Table::association()`` is deprecated. Use ``getAssociation()`` - instead. -* The ``Xcache`` cache engine has been deprecated. The Xcache extension is no - longer actively maintained. If you are using xcache, consider adopting APCu, - Memcached, or Redis instead. -* Passing a list of arrays to ``Router::setRequestInfo()`` is now deprecated. - Pass an instance of ``ServerRequest`` instead. -* ``Cake\Controller\Controller:$name`` is protected now. Use - ``Controller::getName()/setName()`` to access a controller's name in other - contexts. -* ``Cake\Controller\Controller:$plugin`` is protected now. Use - ``Controller::getPlugin()/setPlugin()`` to access a controller's plugin in - other contexts. -* ``Cake\Controller\Controller:$autoRender`` is protected now. Use - ``enableAutoRender()/disableAutoRender()/isAutoRenderEnabled()`` instead. -* The setter mode of ``ValidationSet::isPresenceRequired()`` and - ``ValidationSet::isEmptyAllowed()`` are deprecated. Use ``requirePresence()`` - and ``allowEmpty()`` instead. -* ``Cake\Form\Form::validator()`` is deprecated. Use ``getValidator()`` and - ``setValidator()`` instead. -* ``Cake\ORM\TableRegistry`` static API has been deprecated. Use a table locator - directly instead. A global ``Cake\ORM\Locator\TableLocator`` instance can be - accessed via ``Cake\ORM\TableRegistry::getTableLocator()`` or using a - ``Cake\ORM\Locator\LocatorAwareTrait``. -* ``Cake\View\Helper\FormHelper::widgetRegistry()`` is deprecated. Use - ``getWidgetLocator()`` and ``setWidgetLocator()`` instead. -* ``Cake\ORM\Behavior\TranslateBehavior::locale()`` is deprecated. Use - ``getLocale()`` and ``setLocale()`` instead. -* The getter part of ``Cake\Datasource\QueryTrait::formatResults()`` is deprecated. Use - ``getResultFormatters()`` instead. -* The getter part of ``Cake\Datasource\QueryTrait::mapReduce()`` is deprecated. Use - ``getMapReducers()`` instead. -* The getter part of ``Cake\ORM\Query::contain()`` is deprecated. Use - ``getContain()`` instead. -* The getter part of ``Cake\Datasource\QueryInterface::repository()`` - is deprecated. Use ``getRepository()`` instead. - -Several classes were *renamed*. Their old names will continue to work until 4.0, -but will emit deprecation warnings: - -* ``Cake\Network\Exception\BadRequestException`` has been renamed to - ``Cake\Http\Exception\BadRequestException``. -* ``Cake\Network\Exception\ConflictException`` has been renamed to - ``Cake\Http\Exception\ConflictException``. -* ``Cake\Network\Exception\ForbiddenException`` has been renamed to - ``Cake\Http\Exception\ForbiddenException``. -* ``Cake\Network\Exception\GoneException`` has been renamed to - ``Cake\Http\Exception\GoneException``. -* ``Cake\Network\Exception\HttpException`` has been renamed to - ``Cake\Http\Exception\HttpException``. -* ``Cake\Network\Exception\InternalErrorException`` has been renamed to - ``Cake\Http\Exception\InternalErrorException``. -* ``Cake\Network\Exception\InvalidCsrfTokenException`` has been renamed to - ``Cake\Http\Exception\InvalidCsrfTokenException``. -* ``Cake\Network\Exception\MethodNotAllowedException`` has been renamed to - ``Cake\Http\Exception\MethodNotAllowedException``. -* ``Cake\Network\Exception\NotAcceptableException`` has been renamed to - ``Cake\Http\Exception\NotAcceptableException``. -* ``Cake\Network\Exception\NotFoundException`` has been renamed to - ``Cake\Http\Exception\NotFoundException``. -* ``Cake\Network\Exception\NotImplementedException`` has been renamed to - ``Cake\Http\Exception\NotImplementedException``. -* ``Cake\Network\Exception\ServiceUnavailableException`` has been renamed to - ``Cake\Http\Exception\ServiceUnavailableException``. -* ``Cake\Network\Exception\UnauthorizedException`` has been renamed to - ``Cake\Http\Exception\UnauthorizedException``. -* ``Cake\Network\Exception\UnavailableForLegalReasonsException`` has been - renamed to ``Cake\Http\Exception\UnavailableForLegalReasonsException``. -* ``Cake\Network\Session`` has been renamed to ``Cake\Http\Session``. -* ``Cake\Network\Session\DatabaseSession`` has been renamed to - ``Cake\Http\Session\DatabaseSession``. -* ``Cake\Network\Session\CacheSession`` has been renamed to - ``Cake\Http\Session\CacheSession``. -* ``Cake\Network\CorsBuilder`` has been renamed to ``Cake\Http\CorsBuilder``. -* ``Cake\View\Widget\WidgetRegistry`` has been renamed to - ``Cake\View\Widget\WidgetLocator``. - -Disabling Deprecation Warnings -============================== - -Deprecation warnings are intended to help you prepare for future versions of -CakePHP, but updating your code will likely be an incremental process. You can -disable deprecation warnings while you work towards adopting the new methods. In -your **config/app.php** you can set ``Error.errorLevel``:: - - // in config/app.php - 'Error' => [ - 'errorLevel' => E_ALL ^ E_USER_DEPRECATED - ] - -Once you have no remaining deprecation warnings you can set your error level to -``E_ALL`` to help prevent future use of deprecated methods. - - -Behavior Changes -================ - -The following changes are API compatible, but they represent minor variances in -behavior that may affect your application: - -* ``Cake\Utility\Security::randomBytes()`` will now throw exceptions when - a secure source of entropy cannot be found in PHP5. -* Tokens generated by ``SecurityComponent`` now include the user's session id, - to prevent token reuse between users/sessions. This changes the value of - security tokens and will cause forms created in earlier versions of CakePHP to - fail validation in 3.6. -* ``Cake\Database\Query::page()`` now raises exceptions when page values are - < 1. -* Pagination now allows sorting on multiple fields across all pages. Previously - only the first page could be sorted by more than one column. Furthermore, sort - conditions defined in the query string are *prepended* to the default order - parameters now instead of fully replacing the default ordering. -* Shell classes will now throw exceptions when task classes cannot be found. - Previously invalid tasks would be silently ignored. -* CakePHP internals now chain exceptions where possible, allowing root causes of - errors to be exposed. -* MySQL connections now default to ``utf8mb4`` (4 byte unicode) as their - encoding. If you want to continue using the old default of ``utf8``, set - your application's datasource' encoding in ``config/app.php`` to 'utf8'. -* APCu and Wincache engines no longer set separate ``_expires`` keys for data - with a TTL. Instead they rely on the native TTL features of the cache engine. - By default all entries created with APCu for a single request/CLI script will - have the same expiration time. You can use ``apc.use_request_time`` to change - this behavior. -* ``Router::parseNamedParams()`` no longer mutates the request object in-place. - Instead you will need to use the return value of this method to access the - modified request. -* ``Hash::extract()`` no longer matches integer ``0`` when using attribute - matchers for string values. -* The console environment no longer automatically loads plugins specified by the - ``--plugin`` option. Instead you must ensure that your application - bootstrapping loads all the required plugins. -* ``Cake\Http\CorsBuilder::build()`` no longer mutates the response in place. - You must now use the updated response that ``build()`` returns. - -Cache -===== - -* Fallback engines can be disabled by setting ``fallback = false`` for any cache - configuration. - -Collection -========== - -* The ``appendItem()``, ``prepend()``, ``prependItems()`` methods were added to - ``CollectionTrait``. - -Configure -========= - -* ``consumeOrFail()`` has been added to complete the API for reading with the expectation of data being present. - -Console -======= - -A new way to build CLI tools has been added. Shell & Tasks have several -shortcomings that are hard to correct without breaking compatibility. -``Cake\Console\Command`` will replace ``Shell`` long term as the recommended way -to build console applications. See the :doc:`/console-and-shells/commands` -section for more information. - -* ``ConsoleOptionParse::enableSubcommandSort()`` was added. This method allows - you to disable the automatic sorting of subcommands in generated help text. - - -Core -==== - -* Plugins can now define :ref:`plugin-objects`. These classes are optional and - allow a plugin to add middleware and console commands to the host application. - They are a class based way to configure and define a plugin. -* ``getTypeName()`` was added to assist in getting correct class/type name when - building more descriptive error messages. - -Database -======== - -* ``Query::identifier()`` was added. This method makes it easier to create - identifier expressions for use in complex queries. -* Database connections will automatically be re-established when connections - timeout during long running scripts. -* ``Cake\Database\Type\BatchCastingInterface`` was added. This interface allows - type classes to optimize casting operations by operating on all columns in - bulk. This interface can be used in custom types now, and will be used in core - types in 4.x. -* ``Cake\Database\Type\DateTimeType::setTimezone()`` was added. This method lets - you set the timezone that datetime objects should be converted to before - inserting into the database. It does not change datetime data being read from - the database. -* ``Cake\Database\Statement\StatementDecorator::fetchAssoc()`` was added. -* ``Cake\Database\Statement\BufferedStatement::fetchAssoc()`` was added. -* ``Cake\Database\Statement\StatementDecorator::FETCH_TYPE_NUM`` was added. -* ``Cake\Database\Statement\StatementDecorator::FETCH_TYPE_ASSOC`` was added. -* ``Cake\Database\Statement\StatementDecorator::FETCH_TYPE_OBJ`` was added. - -Datasource -========== - -* A new abstract type was added for ``binaryuuid``. In MySQL and SQLite, - ``BINARY(16)`` will be used as the column type. While in SQLServer, and - Postgres will use their native UUID types. - -Event -===== - -* ``Cake\Event\EventInterface`` was added to give allow better typehinting in - the future. - -Form -==== - -* Form classes now support the ``_validatorClass`` property which works the same - as it does on ``ORM\Table``. - -Http -==== - -* ``Response::withAddedLink()`` was added to make creating ``Link`` headers - simpler. -* ``BodyParserMiddleware`` was added. - -I18n -==== - -* The two leftover FormHelper i18n translation strings ``'Edit %s'`` and ``'New - %s'`` are now ``'Edit {0}'`` and ``'New {0}'``. If you are using translating - messages from CakePHP, please make sure you adjust those translations in your - PO file. - -Mailer -====== - -* The various email address setter methods on ``Email`` now accept ``[]`` - allowing individual properties to be reset. - -ORM -=== - -* ``EntityTrait::isEmpty()`` and ``EntityTrait::hasValue()`` were added. -* ``Table::getAssociation()`` can now read deeply nested associations using - ``.`` separated paths. e.g ``Users.Comments``. This method will raise - exceptions when getting an unknown association now. -* ``Table::addBehaviors()`` was added making it simpler to add multiple - behaviors at once. -* ``Table::getBehavior()`` was added. -* ``CounterCacheBehavior`` callback functions can now return ``false`` to skip - updating the counter value. -* ``TimestampBehavior`` now uses the correct mutable/immutable class type when - creating time objects instead of always using a mutable time instance. -* ``Query::selectAllExcept()`` was added. -* ``Query::whereInList()``/``Query::whereNotInList()`` have been added as standalone wrappers around ``IN``/``NOT IN`` conditions. - -Routing -======= - -* ``Cake\Routing\Route\EntityRoute`` was added. This route class makes building - routes that need data from entities easier. See the :ref:`entity-routing` - section for more information. -* Routing variables can now use ``{var}`` style placeholders. This style allows - mid-word variables to be defined. You cannot combine ``{var}`` placeholders - with ``:var`` style placeholders. -* ``Router::routeExists()`` was added. This method lets you check if a route - array can be resolved into a valid route. -* Route connection can now use compact 'string targets' e.g - ``Bookmarks::index``. See :ref:`routes-configuration` for more information. -* ``RoutingMiddleware`` can now cache the route collection created by your - routes. Caching routes greatly improves application startup times. - It now also requires to be instantiated and the current object (``$this``) passed for plugin routing. - -Shell -===== - -* The ``cake assets copy`` command now features an ``--overwrite`` option for - overwriting plugin assets if they already exist in the application webroot. - -Utility -======= - -* ``Security::randomString()`` was added. - -Validation -========== - -* ``Validation::compareFields()`` was added as a more flexible version of - ``Validation::compareWith()``. -* ``Validator::notSameAs()`` was added to make it - easier to check if a field is not the same as another field. -* New field comparison methods were added. ``equalToField()``, - ``notEqualToField()``, ``greaterThanField()``, - ``greaterThanOrEqualToField()``, ``lessThanField()``, - ``lessThanOrEqualToField()`` were added. -* Validator rules will now use the rule alias as the rule method when the - ``rule`` key is not defined. -* ``Validator::addNested()`` and ``addNestedMany()`` now support the ``when`` - and ``message`` parameters like other validator methods. - -View -==== - -* ``UrlHelper::script()``, ``css()``, and ``image()`` methods now support - a ``timestamp`` option which allows you to set the ``Asset.timestamp`` - setting for a single method call. -* Cell classes now have an ``initialize()`` hook method. -* ``PaginatorHelper`` will now reset the page to 1 each time sort directions are - changed. diff --git a/en/appendices/3-7-migration-guide.rst b/en/appendices/3-7-migration-guide.rst deleted file mode 100644 index ec0568950e..0000000000 --- a/en/appendices/3-7-migration-guide.rst +++ /dev/null @@ -1,295 +0,0 @@ -3.7 Migration Guide -################### - -CakePHP 3.7 is an API compatible upgrade from 3.6. This page outlines the -changes and improvements made in 3.7. - -To upgrade to 3.7.x run the following composer command: - -.. code-block:: bash - - php composer.phar require --update-with-dependencies "cakephp/cakephp:3.7.*" - -Deprecations -============ - -The following is a list of deprecated methods, properties and behaviors. These -features will continue to function until 4.0.0 after which they will be removed. - -* ``Cake\Form\Form::errors()`` is deprecated. Use ``getErrors()`` instead. -* ``Cake\Http\Client\Response::$headers`` is deprecated. Use ``getHeaders()`` or - ``getHeaderLine()`` instead. -* ``Cake\Http\Client\Response::$body`` is deprecated. Use ``getStringBody()`` - instead. -* ``Cake\Http\Client\Response::$json`` is deprecated. Use ``getJson()`` - instead. -* ``Cake\Http\Client\Response::$xml`` is deprecated. Use ``getXml()`` - instead. -* ``Cake\Http\Client\Response::$cookies`` is deprecated. Use ``getCookies()`` - instead. -* ``Cake\Http\Client\Response::$code`` is deprecated. Use ``getStatusCode()`` - instead. -* ``Cake\Http\Client\Response::body()`` is deprecated. Use ``getStringBody()`` - instead. -* ``Cake\ORM\Association::className()`` has been deprecated. Use - ``getClassName()`` and ``setClassName()`` instead. -* Using ``Cake\Database\Query::join()`` to read information is deprecated. - Instead use ``Query::clause('join')``. -* Using ``Cake\Database\Query::from()`` to read information is deprecated. - Instead use ``Query::clause('from')``. -* ``Cake\Database\Connection::logQueries()`` is deprecated. Use - ``enableQueryLogging()`` and ``isQueryLoggingEnabled()`` instead. -* The string/array parameter set for ``Cake\Http\Response::withCookie()`` is - deprecated. Instead you need to pass in ``Cake\Http\Cookie\Cookie`` instances. -* ``Cake\Validation\Validation::cc()`` has been renamed to ``creditCard()``. -* ``Cake\View\ViewVarsTrait::viewOptions()`` is deprecated. Use - ``viewBuilder()->setOptions()`` instead. -* ``Cake\View\View::$request`` is protected now. Use - ``View::getRequest()/setRequest()`` to access a View's request instance in - other contexts. -* ``Cake\View\View::$response`` is protected now. Use - ``View::getResponse()/setResponse()`` to access a View's response instance in - other contexts. -* ``Cake\View\View::$templatePath`` is protected now. Use - ``getTemplatePath()/setTemplatePath()`` instead. -* ``Cake\View\View::$template`` is protected now. Use - ``getTemplate()/setTemplate()`` instead. -* ``Cake\View\View::$layout`` is protected now. Use ``getLayout()/setLayout()`` - instead. -* ``Cake\View\View::$layoutPath`` is protected now. Use - ``getLayoutPath()/setLayoutPath()`` instead. -* ``Cake\View\View::$autoLayout`` is protected now. Use - ``enableAutoLayout()/isAutoLayoutEnabled()`` instead. -* ``Cake\View\View::$theme`` is protected now. Use - ``getTheme()/setTheme()`` instead. -* ``Cake\View\View::$subDir`` is protected now. Use ``getSubDir()/setSubDir()`` instead. -* ``Cake\View\View::$plugin`` is protected now. Use ``getPlugin()/setPlugin()`` - instead. -* ``Cake\View\View::$name`` is protected now. Use ``getName()/setName()`` - instead. -* ``Cake\View\View::$elementCache`` is protected now. Use - ``getElementCache()/setElementCache()`` instead. -* ``Cake\View\View::$Blocks`` is protected now. Use public methods on View to - interact with blocks. -* ``Cake\View\View:$helpers`` is protected now. Use ``helpers()`` to interact - with the HelperRegistry instead. -* ``Cake\View\View::$uuids`` is deprecated and will be removed in 4.0 -* ``Cake\View\View::uuid()`` is deprecated and will be removed in 4.0 -* ``Cake\View\Cell::$template`` is protected now. Use - ``viewBuilder()->getTemplate()/setTemplate()`` instead. -* ``Cake\View\Cell::$plugin`` is protected now. Use - ``viewBuilder()->getPlugin()/setPlugin()`` instead. -* ``Cake\View\Cell::$helpers`` is protected now. Use - ``viewBuilder()->getHelpers()/setHelpers()`` instead. -* ``Cake\View\Cell::$action`` is protected now. -* ``Cake\View\Cell::$args`` is protected now. -* ``Cake\View\Cell::$View`` is protected now. -* ``Cake\View\Cell::$request`` is protected now. -* ``Cake\View\Cell::$response`` is protected now. -* ``Cake\View\ViewVarsTrait::$viewVars`` is deprecated. This public property - will be removed in 4.0.0. Use ``set()`` instead. -* ``Cake\Filesystem\Folder::normalizePath()`` is deprecated. You should use - ``correctSlashFor()`` instead. -* ``Cake\Mailer\Email::setConfigTransport()`` is deprecated. Use - ``Cake\Mailer\TransportFactory::setConfig()`` instead. -* ``Cake\Mailer\Email::getConfigTransport()`` is deprecated. Use - ``Cake\Mailer\TransportFactory::getConfig()`` instead. -* ``Cake\Mailer\Email::configTransport()`` is deprecated. Use - ``Cake\Mailer\TransportFactory::getConfig()/setConfig()`` instead. -* ``Cake\Mailer\Email::configuredTransport()`` is deprecated. Use - ``Cake\Mailer\TransportFactory::configured()`` instead. -* ``Cake\Mailer\Email::dropTransport()`` is deprecated. Use - ``Cake\Mailer\TransportFactory::drop()`` instead. -* Following view related methods of ``Cake\Mailer\Email`` have been deprecated: - ``setTemplate()``, ``getTemplate()``, ``setLayout()``, ``getLayout()``, - ``setTheme()``, ``getTheme()``, ``setHelpers()``, ``getHelpers()``. - Use the same methods through Email's view builder instead. For e.g. - ``$email->viewBuilder()->getTemplate()``. -* ``Cake\Mailer\Mailer::layout()`` is deprecated. - Use ``$mailer->viewBuilder()->setLayout()`` instead. -* ``Helper::$theme`` is removed. Use ``View::getTheme()`` instead. -* ``Helper::$plugin`` is removed. Use ``View::getPlugin()`` instead. -* ``Helper::$fieldset`` and ``Helper::$tags`` are deprecated as they are unused. -* ``Helper::$helpers`` is now protected and should not be accessed from outside - a helper class. -* ``Helper::$request`` is removed. - Use ``View::getRequest()``, ``View::setRequest()`` instead. -* ``Cake\Core\Plugin::load()`` and ``loadAll()`` are deprecated. Instead you - should use ``Application::addPlugin()``. -* ``Cake\Core\Plugin::unload()`` is deprecated. Use - ``Plugin::getCollection()->remove()`` or ``clear()`` instead. -* The following properties of ``Cake\Error\ExceptionRender`` are now protected: - ``$error``, ``$controller``, ``$template`` and ``$method``. -* Using underscored fixtures names in ``TestCase::$fixtures`` is deprecated. - Use CamelCased names instead. For e.g. ``app.FooBar``, ``plugin.MyPlugin.FooBar``. - -Soft Deprecations -================= - -The following methods, properties and features have been deprecated but will not -be removed until 5.0.0: - -* ``Cake\TestSuite\ConsoleIntegrationTestCase`` is deprecated. You should - include ``Cake\TestSuite\ConsoleIntegrationTestTrait`` into your test case - class instead. - -Behavior Changes -================ - -* ``Cake\Database\Type\IntegerType`` will now raise an exception when values - are not numeric when preparing SQL statements and converting database results - to PHP types. -* ``Cake\Database\Statement\StatementDecorator::fetchAll()`` now returns an - empty array instead of ``false`` when no result is found. -* ``Cake\Database\Statement\BufferedStatement`` no longer inherits from - ``StatementDecorator`` and no longer implements the ``IteratorAggregate`` - interface. Instead it directly implements the ``Iterator`` interface to better - support using statements with collections. -* When marshalling data from the request into entities, the ORM will now convert - non-scalar data into ``null`` for boolean, integer, float, and decimal types. -* ``ExceptionRenderer`` will now **always** call handler methods for custom - application exception classes. Previously, custom exception class handler - methods would only be invoked in debug mode. -* ``Router::url()`` will now default the ``_method`` key to ``GET`` when - generating URLs with ``Router::url()``. - - -New Features -============ - -Cache ------ - -* The ``ArrayEngine`` was added. This engine provides an ephemeral in memory - cache implementation. It is ideal for test suites or long running processes - where you don't want persistent cache storage. - -Database --------- - -* ``Cake\Database\FunctionsBuilder::rand()`` was added. - -Datasource ----------- - -* ``Paginator`` will now match unprefixed ``sort`` values in the query string to - the primary model if there also exists a matching model prefixed default sort - field. As an example, if your controller defines a default sort of - ``['Users.name' => 'desc']`` you can now use either ``Users.name`` or ``name`` - as your sort key. - -Error ------ - -* ``ExceptionRenderer`` will now look for prefixed error controllers when - handling exceptions. This allows you to define custom error controller logic - for each routing prefix in your application. -* ``ErrorHandlerMiddleware`` will now include previous exceptions in logging. - -Filesystem ----------- - -* ``Cake\Filesystem\Folder::normalizeFullPath()`` was added. - -Form ----- - -* ``Cake\Form\Form::setData()`` was added. This method makes defining default - values for forms simpler. -* ``Cake\Form\Form::getData()`` was added. - -Http ----- - -* ``Cake\Http\ServerRequest::setTrustedProxies()`` was added. -* ``Cake\Http\Client`` will now default to use a Curl based adapter if the - ``curl`` extension is installed. -* New constants have been added to the ``SecurityHeadersMiddleware``. The new - constants are used to build the components of HTTP headers. - -Mailer ------- - -* ``Cake\Mailer\TransportFactory`` and ``Cake\Mailer\TransportRegistry`` were - added. This class extracts transport creation out of Email, allowing Email to - become simpler in the future. - -ORM ---- - -* ``Cake\ORM\EntityTrait::hasErrors()`` was added. This method can be used to - check whether or not an entity has errors more efficiently than - ``getErrors()`` does. -* Updating has many association data now respects ``_ids``. This makes patching - has many associations work the same as creating new entities, and creates - consistency with belongs to many associations. - -Shell ------ - -* ``cake i18n extract`` has a new ``--relative-paths`` option that makes path - comments in POT files relative to the application root directory instead of - absolute paths. -* ``cake i18n extract`` has a new ``--marker-error`` option that enables - reporting of translation functions that use non-static values as comments in - POT files. - - - -TestSuite ---------- - -* New assertion methods were added to ``IntegrationTestCase``: - - * ``assertResponseNotEquals()`` - * ``assertHeaderNotContains()`` - * ``assertRedirectNotContains()`` - * ``assertFlashElement()`` - * ``assertFlashElementAt()`` - -* The custom assertions provided by ``IntegrationTestCase`` and - ``ConsoleIntegrationTestCase`` are now implemented through constraint classes. -* ``TestCase::loadPlugins()``, ``removePlugins()`` and ``clearPlugins()`` were - added to make working with dynamically loaded plugins easier now that - ``Plugin::load()`` and ``Plugin::unload()`` are deprecated. -* ``getMockForModel()`` now supports ``null`` for the ``$methods`` parameter. - This allows you to create mocks that still execute the original code. This - aligns the behavior with how PHPUnit mock objects work. -* Added ``EmailTrait`` to help facilitate testing emails. -* The default messages for integration assertions have been improved to provide - more context from the exception that was raised if possible. - - -Utility -------- - -* ``Cake\Utility\Text::getTransliterator()`` was added. -* ``Cake\Utility\Text::setTransliterator()`` was added. -* ``Cake\Utility\Xml::loadHtml()`` was added. - -Validation ----------- - -* ``Cake\Validation\Validation::iban()`` was added for validating international - bank account numbers. -* ``Cake\Validation\Validator::allowEmptyString()``, ``allowEmptyArray()``, - ``allowEmptyDate()``, ``allowEmptyTime()``, ``allowEmptyDateTime()``, and - ``allowEmptyFile()`` were added. These new methods replace ``allowEmpty()`` - and give you more control over what a field should consider empty. - -View ----- - -* ``FormHelper`` now supports a ``confirmJs`` template variable which allows the - javascript snippet generated for confirmation boxes to be customized. -* ``FormHelper`` now has a ``autoSetCustomValidity`` option for setting HTML5 - validity messages from custom validation messages. See: :ref:`html5-validity-messages` -* ``ViewBuilder`` had ``setVar()``, ``setVars()``, ``getVar()``, ``getVars()`` and - ``hasVar()`` added. These methods will replace the public ``viewVars`` - property defined in ``ViewVarsTrait``. -* ``PaginatorHelper`` will now match unprefixed sort keys to model prefixed ones - on the default model. This allow smooth operation with the changes made in - ``Cake\Datasource\Paginator`` -* ``FormHelper`` will now read ``maxLength`` validator rules and use them to - automatically define the ``maxlength`` attribute on HTML inputs if a max - length is not provided in the input options. diff --git a/en/appendices/3-8-migration-guide.rst b/en/appendices/3-8-migration-guide.rst deleted file mode 100644 index f65164f12e..0000000000 --- a/en/appendices/3-8-migration-guide.rst +++ /dev/null @@ -1,28 +0,0 @@ -3.8 Migration Guide -################### - -CakePHP 3.8 is an API compatible upgrade from 3.7. This page outlines the -changes and improvements made in 3.8. - -To upgrade to 3.8.x run the following composer command: - -.. code-block:: bash - - php composer.phar require --update-with-dependencies "cakephp/cakephp:3.8.*" - -Behavior Changes -================ - -* ``Cake\ORM\Table::findOrCreate()`` now throws a ``PersistenceFailedException`` - if the find fails and the entity created from ``$search`` contains invalid - data. Previously an invalid entity would be saved. - -New Features -============ - -ORM ---- - -* ``Cake\ORM\Locator\TableLocator`` can now locate table classes in alternative - locations. You can either provide a list of namespaces to the constructor, or - use the ``addLocation()`` method. diff --git a/en/appendices/3-x-migration-guide.rst b/en/appendices/3-x-migration-guide.rst deleted file mode 100644 index 4f3915beb4..0000000000 --- a/en/appendices/3-x-migration-guide.rst +++ /dev/null @@ -1,92 +0,0 @@ -3.x Migration Guide -################### - -.. toctree:: - :hidden: - -Migration guides contain information regarding the new features introduced in -each version and the migration path between 2.x and 3.x. If you are currently -using 1.x you should first upgrade to 2.x. See the 2.x documentation for the -relevant upgrade guides. - -4.0 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 4-0-migration-guide - -3.8 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-8-migration-guide - -3.7 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-7-migration-guide - -3.6 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-6-migration-guide - - -3.5 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-5-migration-guide - -3.4 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-4-migration-guide - -3.3 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-3-migration-guide - -3.2 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-2-migration-guide - -3.1 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-1-migration-guide - -3.0 Migration Guide -=================== - -.. toctree:: - :maxdepth: 1 - - 3-0-migration-guide - orm-migration diff --git a/en/appendices/orm-migration.rst b/en/appendices/orm-migration.rst deleted file mode 100644 index c065f2ab6b..0000000000 --- a/en/appendices/orm-migration.rst +++ /dev/null @@ -1,605 +0,0 @@ -New ORM Upgrade Guide -##################### - -CakePHP 3.0 features a new ORM that has been re-written from the ground up. -While the ORM used in 1.x and 2.x has served us well for a long time it had -a few issues that we wanted to fix. - -* Frankenstein - Is it a record, or a table? Currently it's both. -* Inconsistent API - Model::read() for example. -* No query object - Queries are always defined as arrays, this has some - limitations and restrictions. For example it makes doing unions and - sub-queries much harder. -* Returns arrays - This is a common complaint about CakePHP, and has probably - reduced adoption at some levels. -* No record object - This makes attaching formatting methods - difficult/impossible. -* Containable - Should be part of the ORM, not a crazy hacky behavior. -* Recursive - This should be better controlled as defining which associations - are included, not a level of recursiveness. -* DboSource - It is a beast, and Model relies on it more than datasource. That - separation could be cleaner and simpler. -* Validation - Should be separate, it's a giant crazy function right now. Making - it a reusable bit would make the framework more extensible. - -The ORM in CakePHP 3.0 solves these and many more problems. The new ORM -focuses on relational data stores right now. In the future and through plugins -we will add non relational stores like ElasticSearch and others. - -Design of the New ORM -===================== - -The new ORM solves several problems by having more specialized and focused -classes. In the past you would use ``Model`` and a Datasource for all -operations. Now the ORM is split into more layers: - -* ``Cake\Database\Connection`` - Provides a platform independent way to create - and use connections. This class provides a way to use transactions, - execute queries and access schema data. -* ``Cake\Database\Dialect`` - The classes in this namespace provide platform - specific SQL and transform queries to work around platform specific - limitations. -* ``Cake\Database\Type`` - Is the gateway class to CakePHP database type - conversion system. It is a pluggable framework for adding abstract column - types and providing mappings between database, PHP representations and PDO - bindings for each data type. For example datetime columns are represented as - ``DateTime`` instances in your code now. -* ``Cake\ORM\Table`` - The main entry point into the new ORM. Provides access - to a single table. Handles the definition of association, use of behaviors and - creation of entities and query objects. -* ``Cake\ORM\Behavior`` - The base class for behaviors, which act very similar - to behaviors in previous versions of CakePHP. -* ``Cake\ORM\Query`` - A fluent object based query builder that replaces - the deeply nested arrays used in previous versions of CakePHP. -* ``Cake\ORM\ResultSet`` - A collection of results that gives powerful tools - for manipulating data in aggregate. -* ``Cake\ORM\Entity`` - Represents a single row result. Makes accessing data - and serializing to various formats a snap. - -Now that you are more familiar with some of the classes you'll interact with -most frequently in the new ORM it is good to look at the three most important -classes. The ``Table``, ``Query`` and ``Entity`` classes do much of the heavy -lifting in the new ORM, and each serves a different purpose. - -Table Objects -------------- - -Table objects are the gateway into your data. They handle many of the tasks that -``Model`` did in previous releases. Table classes handle tasks like: - -- Creating queries. -- Providing finders. -- Validating and saving entities. -- Deleting entities. -- Defining and accessing associations. -- Triggering callback events. -- Interacting with behaviors. - -The documentation chapter on :doc:`/orm/table-objects` provides far more detail -on how to use table objects than this guide can. Generally when moving existing -model code over it will end up in a table object. Table objects don't contain -any platform dependent SQL. Instead they collaborate with entities and the query -builder to do their work. Table objects also interact with behaviors and other -interested parties through published events. - -Query Objects -------------- - -While these are not classes you will build yourself, your application code will -make extensive use of the :doc:`/orm/query-builder` which is central to the new -ORM. The query builder makes it easy to build simple or complex queries -including those that were previously very difficult in CakePHP like ``HAVING``, -``UNION`` and sub-queries. - -The various find() calls your application has currently will need to be updated -to use the new query builder. The Query object is responsible for containing the -data to make a query without executing the query itself. It collaborates with -the connection/dialect to generate platform specific SQL which is executed -creating a ``ResultSet`` as the output. - -Entity Objects --------------- - -In previous versions of CakePHP the ``Model`` class returned dumb arrays that -could not contain any logic or behavior. While the community made this -short-coming less painful with projects like CakeEntity, the array results were -often a short coming that caused many developers trouble. For CakePHP 3.0, the -ORM always returns object result sets unless you explicitly disable that -feature. The chapter on :doc:`/orm/entities` covers the various tasks you can -accomplish with entities. - -Entities are created in one of two ways. Either by loading data from the -database, or converting request data into entities. Once created, entities allow -you to manipulate the data they contain and persist their data by collaborating -with table objects. - -Key Differences -=============== - -The new ORM is a large departure from the existing ``Model`` layer. There are -many important differences that are important in understanding how the new ORM -operates and how to update your code. - -Inflection Rules Updated ------------------------- - -You may have noticed that table classes have a pluralized name. In addition to -tables having pluralized names, associations are also referred in the plural -form. This is in contrast to ``Model`` where class names and association aliases -were singular. There are a few reasons for this change: - -* Table classes represent **collections** of data, not single rows. -* Associations link tables together, describing the relations between many - things. - -While the conventions for table objects are to always use plural forms, your -entity association properties will be populated based on the association type. - -.. note:: - - BelongsTo and HasOne associations will use the singular form in entity - properties, while HasMany and BelongsToMany (HABTM) will use plural forms. - -The convention change for table objects is most apparent when building queries. -Instead of expressing queries like:: - - // Wrong - $query->where(['User.active' => 1]); - -You need to use the plural form:: - - // Correct - $query->where(['Users.active' => 1]); - -Find returns a Query Object ---------------------------- - -One important difference in the new ORM is that calling ``find`` on a table will -not return the results immediately, but will return a Query object; this serves -several purposes. - -It is possible to alter queries further, after calling ``find``:: - - $articles = TableRegistry::get('Articles'); - $query = $articles->find(); - $query->where(['author_id' => 1])->order(['title' => 'DESC']); - -It is possible to stack custom finders to append conditions, sorting, limit and -any other clause to the same query before it is executed:: - - $query = $articles->find('approved')->find('popular'); - $query->find('latest'); - -You can compose queries one into the other to create subqueries easier than -ever:: - - $query = $articles->find('approved'); - $favoritesQuery = $article->find('favorites', ['for' => $user]); - $query->where(['id' => $favoritesQuery->select(['id'])]); - -You can decorate queries with iterators and call methods without even touching -the database. This is great when you have parts of your view cached and having -the results taken from the database is not actually required:: - - // No queries made in this example! - $results = $articles->find() - ->order(['title' => 'DESC']) - ->formatResults(function (\Cake\Collection\CollectionInterface $results) { - return $results->extract('title'); - }); - -Queries can be seen as the result object, trying to iterate the query, calling -``toArray()`` or any method inherited from :doc:`collection `, -will result in the query being executed and results returned to you. - -The biggest difference you will find when coming from CakePHP 2.x is that -``find('first')`` does not exist anymore. There is a trivial replacement for it, -and it is the ``first()`` method:: - - // Before - $article = $this->Article->find('first'); - - // Now - $article = $this->Articles->find()->first(); - - // Before - $article = $this->Article->find('first', [ - 'conditions' => ['author_id' => 1] - ]); - - // Now - $article = $this->Articles->find('all', [ - 'conditions' => ['author_id' => 1] - ])->first(); - - // Can also be written - $article = $this->Articles->find() - ->where(['author_id' => 1]) - ->first(); - -If you are loading a single record by its primary key, it will be better to -just call ``get()``:: - - $article = $this->Articles->get(10); - -Finder Method Changes ---------------------- - -Returning a query object from a find method has several advantages, but comes at -a cost for people migrating from 2.x. If you had some custom find methods in -your models, they will need some modifications. This is how you create custom -finder methods in 3.0:: - - class ArticlesTable - { - - public function findPopular(Query $query, array $options) - { - return $query->where(['times_viewed' > 1000]); - } - - public function findFavorites(Query $query, array $options) - { - $for = $options['for']; - return $query->matching('Users.Favorites', function ($q) use ($for) { - return $q->where(['Favorites.user_id' => $for]); - }); - } - } - -As you can see, they are pretty straightforward, they get a Query object instead -of an array and must return a Query object back. For 2.x users that implemented -afterFind logic in custom finders, you should check out the :ref:`map-reduce` -section, or use the features found on the -:doc:`collection objects `. If in your -models you used to rely on having an afterFind for all find operations you can -migrate this code in one of a few ways: - -1. Override your entity constructor method and do additional formatting there. -2. Create accessor methods in your entity to create the virtual fields. -3. Redefine ``findAll()`` and use ``formatResults``. - -In the 3rd case above your code would look like:: - - public function findAll(Query $query, array $options) - { - return $query->formatResults(function (\Cake\Collection\CollectionInterface $results) { - return $results->map(function ($row) { - // Your afterfind logic - }); - }) - } - -You may have noticed that custom finders receive an options array. You can pass -any extra information to your finder using this parameter. This is great -news for people migrating from 2.x. Any of the query keys that were used in -previous versions will be converted automatically for you in 3.x to the correct -functions:: - - // This works in both CakePHP 2.x and 3.0 - $articles = $this->Articles->find('all', [ - 'fields' => ['id', 'title'], - 'conditions' => [ - 'OR' => ['title' => 'Cake', 'author_id' => 1], - 'published' => true - ], - 'contain' => ['Authors'], // The only change! (notice plural) - 'order' => ['title' => 'DESC'], - 'limit' => 10, - ]); - -If your application uses 'magic' or :ref:`dynamic-finders`, you will have to -adapt those calls. In 3.x the ``findAllBy*`` methods have been removed, instead -``findBy*`` always returns a query object. To get the first result, you need to -use the ``first()`` method:: - - $article = $this->Articles->findByTitle('A great post!')->first(); - -Hopefully, migrating from older versions is not as daunting as it first seems. -Many of the features we have added will help you remove code as you can better -express your requirements using the new ORM and at the same time the -compatibility wrappers will help you rewrite those tiny differences in a fast -and painless way. - -One of the other nice improvements in 3.x around finder methods is that -behaviors can implement finder methods with no fuss. By simply defining a method -with a matching name and signature on a Behavior the finder will automatically -be available on any tables the behavior is attached to. - -Recursive and ContainableBehavior Removed ------------------------------------------ - -In previous versions of CakePHP you needed to use ``recursive``, -``bindModel()``, ``unbindModel()`` and ``ContainableBehavior`` to reduce the -loaded data to the set of associations you were interested in. A common tactic -to manage associations was to set ``recursive`` to ``-1`` and use Containable to -manage all associations. In CakePHP 3.0 ContainableBehavior, recursive, -bindModel, and unbindModel have all been removed. Instead the ``contain()`` -method has been promoted to be a core feature of the query builder. Associations -are only loaded if they are explicitly turned on. For example:: - - $query = $this->Articles->find('all'); - -Will **only** load data from the ``articles`` table as no associations have been -included. To load articles and their related authors you would do:: - - $query = $this->Articles->find('all')->contain(['Authors']); - -By only loading associated data that has been specifically requested you spend -less time fighting the ORM trying to get only the data you want. - -No afterFind Event or Virtual Fields ------------------------------------- - -In previous versions of CakePHP you needed to make extensive use of the -``afterFind`` callback and virtual fields in order to create generated data -properties. These features have been removed in 3.0. Because of how ResultSets -iteratively generate entities, the ``afterFind`` callback was not possible. -Both afterFind and virtual fields can largely be replaced with virtual -properties on entities. For example if your User entity has both first and last -name columns you can add an accessor for `full_name` and generate the property -on the fly:: - - namespace App\Model\Entity; - - use Cake\ORM\Entity; - - class User extends Entity - { - protected function _getFullName() - { - return $this->first_name . ' ' . $this->last_name; - } - } - -Once defined you can access your new property using ``$user->full_name``. -Using the :ref:`map-reduce` features of the ORM allow you to build aggregated -data from your results, which is another use case that the ``afterFind`` -callback was often used for. - -While virtual fields are no longer an explicit feature of the ORM, adding -calculated fields is easy to do in your finder methods. By using the query -builder and expression objects you can achieve the same results that virtual -fields gave:: - - namespace App\Model\Table; - - use Cake\ORM\Table; - use Cake\ORM\Query; - - class ReviewsTable extends Table - { - public function findAverage(Query $query, array $options = []) - { - $avg = $query->func()->avg('rating'); - $query->select(['average' => $avg]); - return $query; - } - } - -Associations No Longer Defined as Properties --------------------------------------------- - -In previous versions of CakePHP the various associations your models had were -defined in properties like ``$belongsTo`` and ``$hasMany``. In CakePHP 3.0, -associations are created with methods. Using methods allows us to sidestep the -many limitations class definitions have, and provide only one way to define -associations. Your ``initialize()`` method and all other parts of your application -code, interact with the same API when manipulating associations:: - - namespace App\Model\Table; - - use Cake\ORM\Table; - use Cake\ORM\Query; - - class ReviewsTable extends Table - { - - public function initialize(array $config) - { - $this->belongsTo('Movies'); - $this->hasOne('Ratings'); - $this->hasMany('Comments') - $this->belongsToMany('Tags') - } - - } - -As you can see from the example above each of the association types uses -a method to create the association. One other difference is that -``hasAndBelongsToMany`` has been renamed to ``belongsToMany``. To find out more -about creating associations in 3.0 see the section on :doc:`/orm/associations`. - -Another welcome improvement to CakePHP is the ability to create your own -association classes. If you have association types that are not covered by the -built-in relation types you can create a custom ``Association`` sub-class and -define the association logic you need. - -Validation No Longer Defined as a Property ------------------------------------------- - -Like associations, validation rules were defined as a class property in previous -versions of CakePHP. This array would then be lazily transformed into -a ``ModelValidator`` object. This transformation step added a layer of -indirection, complicating rule changes at runtime. Furthermore, validation rules -being defined as a property made it difficult for a model to have multiple sets -of validation rules. In CakePHP 3.0, both these problems have been remedied. -Validation rules are always built with a ``Validator`` object, and it is trivial -to have multiple sets of rules:: - - namespace App\Model\Table; - - use Cake\ORM\Table; - use Cake\ORM\Query; - use Cake\Validation\Validator; - - class ReviewsTable extends Table - { - - public function validationDefault(Validator $validator) - { - $validator->requirePresence('body') - ->add('body', 'length', [ - 'rule' => ['minLength', 20], - 'message' => 'Reviews must be 20 characters or more', - ]) - ->add('user_id', 'numeric', [ - 'rule' => 'numeric' - ]); - return $validator; - } - - } - -You can define as many validation methods as you need. Each method should be -prefixed with ``validation`` and accept a ``$validator`` argument. - -In previous versions of CakePHP 'validation' and the related callbacks covered -a few related but different uses. In CakePHP 3.0, what was formerly called -validation is now split into two concepts: - -#. Data type and format validation. -#. Enforcing application, or business rules. - -Validation is now applied before ORM entities are created from request data. -This step lets you ensure data matches the data type, format, and basic shape -your application expects. You can use your validators when converting request -data into entities by using the ``validate`` option. See the documentation on -:ref:`converting-request-data` for more information. - -:ref:`Application rules ` allow you to define rules that -ensure your application's rules, state and workflows are enforced. Rules are -defined in your Table's ``buildRules()`` method. Behaviors can add rules using -the ``buildRules()`` hook method. An example ``buildRules()`` method for our -articles table could be:: - - // In src/Model/Table/ArticlesTable.php - namespace App\Model\Table; - - use Cake\ORM\Table; - use Cake\ORM\RulesChecker; - - class ArticlesTable extends Table - { - public function buildRules(RulesChecker $rules) - { - $rules->add($rules->existsIn('user_id', 'Users')); - $rules->add( - function ($article, $options) { - return ($article->published && empty($article->reviewer)); - }, - 'isReviewed', - [ - 'errorField' => 'published', - 'message' => 'Articles must be reviewed before publishing.' - ] - ); - return $rules; - } - } - -Identifier Quoting Disabled by Default --------------------------------------- - -In the past CakePHP has always quoted identifiers. Parsing SQL snippets and -attempting to quote identifiers was both error prone and expensive. If you are -following the conventions CakePHP sets out, the cost of identifier quoting far -outweighs any benefit it provides. Because of this identifier quoting has been -disabled by default in 3.0. You should only need to enable identifier quoting if -you are using column names or table names that contain special characters or are -reserved words. If required, you can enable identifier quoting when configuring -a connection:: - - // In config/app.php - 'Datasources' => [ - 'default' => [ - 'className' => 'Cake\Database\Driver\Mysql', - 'username' => 'root', - 'password' => 'super_secret', - 'host' => 'localhost', - 'database' => 'cakephp', - 'quoteIdentifiers' => true, - ] - ], - -.. note:: - - Identifiers in ``QueryExpression`` objects will not be quoted, and you will - need to quote them manually or use IdentifierExpression objects. - -Updating Behaviors -================== - -Like most ORM related features, behaviors have changed in 3.0 as well. They now -attach to ``Table`` instances which are the conceptual descendant of the -``Model`` class in previous versions of CakePHP. There are a few key -differences from behaviors in CakePHP 2.x: - -- Behaviors are no longer shared across multiple tables. This means you no - longer have to 'namespace' settings stored in a behavior. Each table using - a behavior will get its own instance. -- The method signatures for mixin methods have changed. -- The method signatures for callback methods have changed. -- The base class for behaviors have changed. -- Behaviors can add finder methods. - -New Base Class --------------- - -The base class for behaviors has changed. Behaviors should now extend -``Cake\ORM\Behavior``; if a behavior does not extend this class an exception -will be raised. In addition to the base class changing, the constructor for -behaviors has been modified, and the ``startup()`` method has been removed. -Behaviors that need access to the table they are attached to should define -a constructor:: - - namespace App\Model\Behavior; - - use Cake\ORM\Behavior; - - class SluggableBehavior extends Behavior - { - - protected $_table; - - public function __construct(Table $table, array $config) - { - parent::__construct($table, $config); - $this->_table = $table; - } - - } - -Mixin Methods Signature Changes -------------------------------- - -Behaviors continue to offer the ability to add 'mixin' methods to Table objects, -however the method signature for these methods has changed. In CakePHP 3.0, -behavior mixin methods can expect the **same** arguments provided to the table -'method'. For example:: - - // Assume table has a slug() method provided by a behavior. - $table->slug($someValue); - -The behavior providing the ``slug()`` method will receive only 1 argument, and its -method signature should look like:: - - public function slug($value) - { - // Code here. - } - -Callback Method Signature Changes ---------------------------------- - -Behavior callbacks have been unified with all other listener methods. Instead of -their previous arguments, they need to expect an event object as their first -argument:: - - public function beforeFind(Event $event, Query $query, array $options) - { - // Code. - } - -See :ref:`table-callbacks` for the signatures of all the callbacks a behavior -can subscribe to. diff --git a/en/console-and-shells.rst b/en/console-and-shells.rst index 4f64b0f3e8..75aec129e8 100644 --- a/en/console-and-shells.rst +++ b/en/console-and-shells.rst @@ -208,11 +208,7 @@ CakePHP Provided Commands console-and-shells/server-shell console-and-shells/upgrade-shell console-and-shells/shells - -.. toctree:: - :hidden: - - console-and-shells/orm-cache + console-and-shells/repl Routing in the Console Environment ================================== diff --git a/en/console-and-shells/option-parsers.rst b/en/console-and-shells/option-parsers.rst index 959faebb82..56eddd1970 100644 --- a/en/console-and-shells/option-parsers.rst +++ b/en/console-and-shells/option-parsers.rst @@ -421,4 +421,5 @@ When defining a subcommand you can use the following options: Adding subcommands can be done as part of a fluent method chain. .. deprecated:: 3.6.0 - Subcommands are deprecated. Instead use :ref:`nested commands `. + Subcommands are deprecated and will be removed in 5.0. + Instead use :ref:`nested commands `. diff --git a/en/console-and-shells/orm-cache.rst b/en/console-and-shells/orm-cache.rst deleted file mode 100644 index 8d2ea9848b..0000000000 --- a/en/console-and-shells/orm-cache.rst +++ /dev/null @@ -1,6 +0,0 @@ -ORM Cache Shell -############### - -.. deprecated:: 3.6.0 - The OrmCacheShell is replaced by :doc:`/console-and-shells/schema-cache` - diff --git a/en/contents.rst b/en/contents.rst index 061f400961..00b56e1150 100644 --- a/en/contents.rst +++ b/en/contents.rst @@ -13,7 +13,7 @@ Contents intro quickstart - appendices/3-x-migration-guide + appendices/4-0-migration-guide tutorials-and-examples contributing diff --git a/en/controllers.rst b/en/controllers.rst index 7cd7830bd3..afb771907e 100644 --- a/en/controllers.rst +++ b/en/controllers.rst @@ -441,27 +441,6 @@ CakePHP for you. Read the :ref:`configuring-components` section for more information. As mentioned earlier the ``$components`` property will be merged with the property defined in each of your controller's parent classes. -Configuring Helpers to Load -=========================== - -.. php:attr:: helpers - -Let's look at how to tell a CakePHP Controller that you plan to use -additional MVC classes:: - - class RecipesController extends AppController - { - public $helpers = ['Form']; - } - -Each of these variables are merged with their inherited values, -therefore it is not necessary (for example) to redeclare the -``FormHelper``, or anything that is declared in your ``AppController``. - -.. deprecated:: 3.0 - Loading Helpers from the controller is provided for backwards compatibility - reasons. You should see :ref:`configuring-helpers` for how to load helpers. - .. _controller-life-cycle: Request Life-cycle Callbacks diff --git a/en/controllers/components.rst b/en/controllers/components.rst index f14eaa83d7..5efdf8aa1d 100644 --- a/en/controllers/components.rst +++ b/en/controllers/components.rst @@ -16,8 +16,6 @@ chapter for each component: :maxdepth: 1 /controllers/components/authentication - /controllers/components/cookie - /controllers/components/csrf /controllers/components/flash /controllers/components/security /controllers/components/pagination @@ -29,8 +27,8 @@ Configuring Components ====================== Many of the core components require configuration. Some examples of components -requiring configuration are :doc:`/controllers/components/authentication` and -:doc:`/controllers/components/cookie`. Configuration for these components, +requiring configuration are :doc:`/controllers/components/security` and +:doc:`/controllers/components/request-handling`. Configuration for these components, and for components in general, is usually done via ``loadComponent()`` in your Controller's ``initialize()`` method or via the ``$components`` array:: @@ -43,7 +41,7 @@ Controller's ``initialize()`` method or via the ``$components`` array:: 'authorize' => 'Controller', 'loginAction' => ['controller' => 'Users', 'action' => 'login'] ]); - $this->loadComponent('Cookie', ['expires' => '1 day']); + $this->loadComponent('Security', ['blackholeCallback' => 'blackhole']); } } diff --git a/en/controllers/components/cookie.rst b/en/controllers/components/cookie.rst deleted file mode 100644 index 847ae5f234..0000000000 --- a/en/controllers/components/cookie.rst +++ /dev/null @@ -1,137 +0,0 @@ -Cookie -###### - -.. php:namespace:: Cake\Controller\Component - -.. php:class:: CookieComponent(ComponentRegistry $collection, array $config = []) - -The CookieComponent is a wrapper around the native PHP ``setcookie()`` method. It -makes it easier to manipulate cookies, and automatically encrypt cookie data. -Cookies added through CookieComponent will only be sent if the controller action -completes. - -.. deprecated:: 3.5.0 - Cookies are available in the ``ServerRequest`` see :ref:`request-cookies`. - For encrypted cookies see the :ref:`encrypted-cookie-middleware`. - -Configuring Cookies -=================== - -Cookies can be configured either globally or per top-level name. The global -configuration data will be merged with the top-level configuration. So only need -to override the parts that are different. To configure the global settings use -the ``config()`` method:: - - $this->Cookie->config('path', '/'); - $this->Cookie->config([ - 'expires' => '+10 days', - 'httpOnly' => true - ]); - -To configure a specific key use the ``configKey()`` method:: - - $this->Cookie->configKey('User', 'path', '/'); - $this->Cookie->configKey('User', [ - 'expires' => '+10 days', - 'httpOnly' => true - ]); - -There are a number of configurable values for cookies: - -expires - How long the cookies should last for. Defaults to 1 month. -path - The path on the server in which the cookie will be available on. - If path is set to '/foo/', the cookie will only be available within the - /foo/ directory and all sub-directories such as /foo/bar/ of domain. - The default value is app's base path. -domain - The domain that the cookie is available. To make the cookie - available on all subdomains of example.com set domain to '.example.com'. -secure - Indicates that the cookie should only be transmitted over a secure HTTPS - connection. When set to ``true``, the cookie will only be set if a - secure connection exists. -key - Encryption key used when encrypted cookies are enabled. Defaults to Security.salt. -httpOnly - Set to ``true`` to make HTTP only cookies. Cookies that are HTTP only - are not accessible in JavaScript. Defaults to ``false``. -encryption - Type of encryption to use. Defaults to 'aes'. Can also be 'rijndael' for - backwards compatibility. - -Using the Component -=================== - -The CookieComponent offers a number of methods for working with Cookies. - -.. php:method:: write(mixed $key, mixed $value = null) - - The write() method is the heart of the cookie component. $key is the - cookie variable name you want, and the $value is the information to - be stored:: - - $this->Cookie->write('name', 'Larry'); - - You can also group your variables by using dot notation in the - key parameter:: - - $this->Cookie->write('User.name', 'Larry'); - $this->Cookie->write('User.role', 'Lead'); - - If you want to write more than one value to the cookie at a time, - you can pass an array:: - - $this->Cookie->write('User', - ['name' => 'Larry', 'role' => 'Lead'] - ); - - All values in the cookie are encrypted with AES by default. If you want to - store the values as plain text, be sure to configure the key space:: - - $this->Cookie->configKey('User', 'encryption', false); - -.. php:method:: read(mixed $key = null) - - This method is used to read the value of a cookie variable with the - name specified by $key. :: - - // Outputs "Larry" - echo $this->Cookie->read('name'); - - // You can also use the dot notation for read - echo $this->Cookie->read('User.name'); - - // To get the variables which you had grouped - // using the dot notation as an array use the following - $this->Cookie->read('User'); - - // This outputs something like ['name' => 'Larry', 'role' => 'Lead'] - - .. warning:: - CookieComponent cannot interact with bare strings values that contain - ``,``. The component will attempt to interpret these values as - arrays, leading to incorrect results. Instead you should use - ``$request->getCookie()``. - -.. php:method:: check($key) - - :param string $key: The key to check. - - Used to check whether a key/path exists and has a non-null value. - -.. php:method:: delete(mixed $key) - - Deletes a cookie variable of the name in $key. Works with dot - notation:: - - // Delete a variable - $this->Cookie->delete('bar'); - - // Delete the cookie variable bar, but not everything under foo - $this->Cookie->delete('foo.bar'); - -.. meta:: - :title lang=en: Cookie - :keywords lang=en: array controller,php setcookie,cookie string,controller setup,string domain,default description,string name,session cookie,integers,variables,domain name,null diff --git a/en/controllers/components/csrf.rst b/en/controllers/components/csrf.rst deleted file mode 100644 index 03e4056c4a..0000000000 --- a/en/controllers/components/csrf.rst +++ /dev/null @@ -1,91 +0,0 @@ -Cross Site Request Forgery -########################## - -By enabling the CSRF Component you get protection against attacks. `CSRF -`_ or Cross Site -Request Forgery is a common vulnerability in web applications. It allows an -attacker to capture and replay a previous request, and sometimes submit data -requests using image tags or resources on other domains. - -The CsrfComponent works by setting a cookie to the user's browser. When forms -are created with the :php:class:`Cake\\View\\Helper\\FormHelper`, a hidden field -is added containing the CSRF token. During the ``Controller.startup`` event, if -the request is a POST, PUT, DELETE, PATCH request the component will compare the -request data & cookie value. If either is missing or the two values mismatch the -component will throw a -:php:class:`Cake\\Network\\Exception\\InvalidCsrfTokenException`. - -.. note:: - You should always verify the HTTP method being used before executing to avoid - side-effects. You should :ref:`check the HTTP method ` or - use :php:meth:`Cake\\Http\\ServerRequest::allowMethod()` to ensure the correct - HTTP method is used. - -.. deprecated:: 3.5.0 - You should use :ref:`csrf-middleware` instead of - ``CsrfComponent``. - -Using the CsrfComponent -======================= - -Simply by adding the ``CsrfComponent`` to your components array, -you can benefit from the CSRF protection it provides:: - - public function initialize() - { - parent::initialize(); - $this->loadComponent('Csrf'); - } - -Settings can be passed into the component through your component's settings. -The available configuration options are: - -- ``cookieName`` The name of the cookie to send. Defaults to ``csrfToken``. -- ``expiry`` How long the CSRF token should last. Defaults to browser session. - Accepts ``strtotime`` values as of 3.1 -- ``secure`` Whether or not the cookie will be set with the Secure flag. That is, - the cookie will only be set on a HTTPS connection and any attempt over normal HTTP - will fail. Defaults to ``false``. -- ``field`` The form field to check. Defaults to ``_csrfToken``. Changing this - will also require configuring FormHelper. - -When enabled, you can access the current CSRF token on the request object:: - - $token = $this->request->getParam('_csrfToken'); - -Integration with FormHelper -=========================== - -The CsrfComponent integrates seamlessly with ``FormHelper``. Each time you -create a form with FormHelper, it will insert a hidden field containing the CSRF -token. - -.. note:: - - When using the CsrfComponent you should always start your forms with the - FormHelper. If you do not, you will need to manually create hidden inputs in - each of your forms. - -CSRF Protection and AJAX Requests -================================= - -In addition to request data parameters, CSRF tokens can be submitted through -a special ``X-CSRF-Token`` header. Using a header often makes it easier to -integrate a CSRF token with JavaScript heavy applications, or XML/JSON based API -endpoints. - -Disabling the CSRF Component for Specific Actions -================================================= - -While not recommended, you may want to disable the CsrfComponent on certain -requests. You can do this using the controller's event dispatcher, during the -``beforeFilter()`` method:: - - public function beforeFilter(Event $event) - { - $this->getEventManager()->off($this->Csrf); - } - -.. meta:: - :title lang=en: Csrf - :keywords lang=en: configurable parameters,security component,configuration parameters,invalid request,csrf,submission diff --git a/en/controllers/components/request-handling.rst b/en/controllers/components/request-handling.rst index 51946e76e2..4967939aab 100644 --- a/en/controllers/components/request-handling.rst +++ b/en/controllers/components/request-handling.rst @@ -271,10 +271,6 @@ automatically by using the ``viewClassMap`` setting:: ]); } -.. deprecated:: 3.1.0 - As of 3.1.0 the ``viewClassMap()`` method is deprecated. You should use - ``config()`` to change the viewClassMap at runtime. - .. meta:: :title lang=en: Request Handling :keywords lang=en: handler component,javascript libraries,public components,null returns,model data,request data,content types,file extensions,ajax,meth,content type,array,conjunction,cakephp,insight,php diff --git a/en/controllers/components/security.rst b/en/controllers/components/security.rst index 709b024a5f..2e15eb2411 100644 --- a/en/controllers/components/security.rst +++ b/en/controllers/components/security.rst @@ -231,7 +231,7 @@ CSRF or Cross Site Request Forgery is a common vulnerability in web applications. It allows an attacker to capture and replay a previous request, and sometimes submit data requests using image tags or resources on other domains. To enable CSRF protection features use the -:doc:`/controllers/components/csrf`. +:ref:`csrf-middleware`. Disabling Security Component for Specific Actions ================================================= diff --git a/en/controllers/middleware.rst b/en/controllers/middleware.rst index 0edfb2107f..2756f93422 100644 --- a/en/controllers/middleware.rst +++ b/en/controllers/middleware.rst @@ -382,15 +382,12 @@ CSRF protection can be applied to your entire application, or to specific routin .. note:: - You cannot use both of the following approaches together, you must choose only one. - If you use both approaches together, a CSRF token mismatch error will occur on every `PUT` and `POST` request + You cannot use both of the following approaches together, you must choose + only one. If you use both approaches together, a CSRF token mismatch error + will occur on every `PUT` and `POST` request - -.. warning:: - - You cannot use ``CsrfComponent`` together with ``CsrfProtectionMiddleware``, the warning about conflicting components is not shown until 3.7.0. - -By applying the ``CsrfProtectionMiddleware`` to your Application middleware stack you protect all the actions in application:: +By applying the ``CsrfProtectionMiddleware`` to your Application middleware +stack you protect all the actions in application:: // in src/Application.php use Cake\Http\Middleware\CsrfProtectionMiddleware; @@ -405,7 +402,8 @@ By applying the ``CsrfProtectionMiddleware`` to your Application middleware stac return $middlewareQueue; } -By applying the ``CsrfProtectionMiddleware`` to routing scopes, you can include or exclude specific route groups:: +By applying the ``CsrfProtectionMiddleware`` to routing scopes, you can include +or exclude specific route groups:: // in src/Application.php use Cake\Http\Middleware\CsrfProtectionMiddleware; @@ -420,8 +418,8 @@ By applying the ``CsrfProtectionMiddleware`` to routing scopes, you can include // in config/routes.php Router::scope('/', function (RouteBuilder $routes) { $routes->applyMiddleware('csrf'); - }); - + }); + Options can be passed into the middleware's constructor. The available configuration options are: diff --git a/en/core-libraries/email.rst b/en/core-libraries/email.rst index 99bc896fdc..7f77d543f3 100644 --- a/en/core-libraries/email.rst +++ b/en/core-libraries/email.rst @@ -3,11 +3,6 @@ Email .. php:namespace:: Cake\Mailer -.. warning:: - Before version 3.1, the ``Email`` and ``Transport`` classes were under - the ``Cake\Network\Email`` namespace instead of the ``Cake\Mailer`` - namespace. - .. php:class:: Email(mixed $profile = null) ``Email`` is a new class to send email. With this @@ -23,36 +18,33 @@ First of all, you should ensure the class is loaded:: After you've loaded ``Email``, you can send an email with the following:: $email = new Email('default'); - $email->from(['me@example.com' => 'My Site']) - ->to('you@example.com') - ->subject('About') + $email->setFrom(['me@example.com' => 'My Site']) + ->setTo('you@example.com') + ->setSubject('About') ->send('My message'); Since ``Email``'s setter methods return the instance of the class, you are able to set its properties with method chaining. -``Email`` has several methods for defining recipients - ``to()``, ``cc()``, -``bcc()``, ``addTo()``, ``addCc()`` and ``addBcc()``. The main difference being +``Email`` has several methods for defining recipients - ``setTo()``, ``setCc()``, +``setBcc()``, ``addTo()``, ``addCc()`` and ``addBcc()``. The main difference being that the first three will overwrite what was already set and the latter will just add more recipients to their respective field:: $email = new Email(); - $email->to('to@example.com', 'To Example'); + $email->setTo('to@example.com', 'To Example'); $email->addTo('to2@example.com', 'To2 Example'); // The email's To recipients are: to@example.com and to2@example.com - $email->to('test@example.com', 'ToTest Example'); + $email->setTo('test@example.com', 'ToTest Example'); // The email's To recipient is: test@example.com -.. deprecated:: 3.4.0 - Use ``setFrom()``, ``setTo()``, ``setCc()`` , ``setBcc()`` and ``setSubject()`` instead. - Choosing the Sender ------------------- When sending email on behalf of other people, it's often a good idea to define the -original sender using the Sender header. You can do so using ``sender()``:: +original sender using the Sender header. You can do so using ``setSender()``:: $email = new Email(); - $email->sender('app@example.com', 'MyApp emailer'); + $email->setSender('app@example.com', 'MyApp emailer'); .. note:: @@ -60,9 +52,6 @@ original sender using the Sender header. You can do so using ``sender()``:: person's behalf. This prevents them from getting any messages about deliverability. -.. deprecated:: 3.4.0 - Use ``setSender()`` instead. - .. _email-configuration: Configuration @@ -92,7 +81,7 @@ Instead of passing a string which matches a preset configuration name, you can also just load an array of options:: $email = new Email(); - $email->profile(['from' => 'me@example.org', 'transport' => 'my_custom']); + $email->setProfile(['from' => 'me@example.org', 'transport' => 'my_custom']); // Or in constructor $email = new Email(['from' => 'me@example.org', 'transport' => 'my_custom']); @@ -180,33 +169,33 @@ Defining delivery profiles allows you to consolidate common email settings into re-usable profiles. Your application can have as many profiles as necessary. The following configuration keys are used: -- ``'from'``: Email or array of sender. See ``Email::from()``. -- ``'sender'``: Email or array of real sender. See ``Email::sender()``. -- ``'to'``: Email or array of destination. See ``Email::to()``. -- ``'cc'``: Email or array of carbon copy. See ``Email::cc()``. -- ``'bcc'``: Email or array of blind carbon copy. See ``Email::bcc()``. -- ``'replyTo'``: Email or array to reply the e-mail. See ``Email::replyTo()``. +- ``'from'``: Email or array of sender. See ``Email::setFrom()``. +- ``'sender'``: Email or array of real sender. See ``Email::setSender()``. +- ``'to'``: Email or array of destination. See ``Email::setTo()``. +- ``'cc'``: Email or array of carbon copy. See ``Email::setCc()``. +- ``'bcc'``: Email or array of blind carbon copy. See ``Email::setBcc()``. +- ``'replyTo'``: Email or array to reply the e-mail. See ``Email::setReplyTo()``. - ``'readReceipt'``: Email address or an array of addresses to receive the receipt of read. See ``Email::readReceipt()``. - ``'returnPath'``: Email address or an array of addresses to return if have - some error. See ``Email::returnPath()``. -- ``'messageId'``: Message ID of e-mail. See ``Email::messageId()``. -- ``'subject'``: Subject of the message. See ``Email::subject()``. + some error. See ``Email::setReturnPath()``. +- ``'messageId'``: Message ID of e-mail. See ``Email::setMessageId()``. +- ``'subject'``: Subject of the message. See ``Email::setSubject()``. - ``'message'``: Content of message. Do not set this field if you are using rendered content. - ``'priority'``: Priority of the email as numeric value (usually from 1 to 5 with 1 being the highest). -- ``'headers'``: Headers to be included. See ``Email::headers()``. +- ``'headers'``: Headers to be included. See ``Email::setHeaders()``. - ``'viewRender'``: If you are using rendered content, set the view classname. See ``Email::viewRender()``. - ``'template'``: If you are using rendered content, set the template name. See - ``Email::template()``. -- ``'theme'``: Theme used when rendering template. See ``Email::theme()``. + ``Email::setTemplate()``. +- ``'theme'``: Theme used when rendering template. See ``Email::setTheme()``. - ``'layout'``: If you are using rendered content, set the layout to render. If you want to render a template without layout, set this field to null. See ``Email::template()``. - ``'viewVars'``: If you are using rendered content, set the array with variables to be used in the view. See ``Email::setViewVars()``. -- ``'attachments'``: List of files to attach. See ``Email::attachments()``. -- ``'emailFormat'``: Format of email (html, text or both). See ``Email::emailFormat()``. +- ``'attachments'``: List of files to attach. See ``Email::setAttachments()``. +- ``'emailFormat'``: Format of email (html, text or both). See ``Email::setEmailFormat()``. - ``'transport'``: Transport configuration name. See :php:meth:`~Cake\\Mailer\\Email::configTransport()`. - ``'log'``: Log level to log the email headers and message. ``true`` will use @@ -219,7 +208,7 @@ All these configurations are optional, except ``'from'``. The values of above keys using Email or array, like from, to, cc, etc will be passed as first parameter of corresponding methods. The equivalent for: - ``Email::from('my@example.com', 'My Site')`` + ``$email->setFrom('my@example.com', 'My Site')`` would be defined as ``'from' => ['my@example.com' => 'My Site']`` in your config Setting Headers @@ -228,10 +217,7 @@ Setting Headers In ``Email`` you are free to set whatever headers you want. When migrating to use Email, do not forget to put the ``X-`` prefix in your headers. -See ``Email::headers()`` and ``Email::addHeaders()`` - -.. deprecated:: 3.4.0 - Use ``setHeaders()`` instead of ``headers()``. +See ``Email::setHeaders()`` and ``Email::addHeaders()`` Sending Templated Emails ======================== @@ -246,10 +232,10 @@ and elements just like normal views:: $email = new Email(); $email - ->template('welcome', 'fancy') - ->emailFormat('html') - ->to('bob@example.com') - ->from('app@domain.com') + ->setTemplate('welcome', 'fancy') + ->setEmailFormat('html') + ->setTo('bob@example.com') + ->setFrom('app@domain.com') ->send(); The above would use **templates/email/html/welcome.php** for the view @@ -258,10 +244,10 @@ send multipart templated email messages as well:: $email = new Email(); $email - ->template('welcome', 'fancy') - ->emailFormat('both') - ->to('bob@example.com') - ->from('app@domain.com') + ->setTemplate('welcome', 'fancy') + ->setEmailFormat('both') + ->setTo('bob@example.com') + ->setFrom('app@domain.com') ->send(); This would use the following template files: @@ -287,7 +273,7 @@ You can use helpers in emails as well, much like you can in normal template file By default only the ``HtmlHelper`` is loaded. You can load additional helpers using the ``helpers()`` method:: - $email->helpers(['Html', 'Custom', 'Text']); + $email->setHelpers(['Html', 'Custom', 'Text']); When setting helpers be sure to include 'Html' or it will be removed from the helpers loaded in your email template. @@ -296,7 +282,7 @@ If you want to send email using templates in a plugin you can use the familiar :term:`plugin syntax` to do so:: $email = new Email(); - $email->template('Blog.new_comment', 'Blog.auto_message'); + $email->setTemplate('Blog.new_comment', 'Blog.auto_message'); The above would use template and layout from the Blog plugin as an example. @@ -305,39 +291,34 @@ You can do this using themes by telling Email to use appropriate theme using ``Email::theme()`` method:: $email = new Email(); - $email->template('Blog.new_comment', 'Blog.auto_message'); - $email->theme('TestTheme'); + $email->setTemplate('Blog.new_comment', 'Blog.auto_message'); + $email->setTheme('TestTheme'); This allows you to override the ``new_comment`` template in your theme without modifying the Blog plugin. The template file needs to be created in the following path: **templates/plugin/TestTheme/plugin/Blog/email/text/new_comment.php**. -.. deprecated:: 3.4.0 - Use ``viewBuilder()->setTemplate()`` instead of ``template()``. Use - ``viewBuilder()->setLayout()`` instead of the layout argument of - ``template()``. Use ``viewBuilder()->setTheme()`` instead of ``theme()``. - Sending Attachments =================== -.. php:method:: attachments($attachments) +.. php:method:: setAttachments($attachments) You can attach files to email messages as well. There are a few different formats depending on what kind of files you have, and how you want the filenames to appear in the recipient's mail client: -1. String: ``$email->attachments('/full/file/path/file.png')`` will attach this +1. String: ``$email->setAttachments('/full/file/path/file.png')`` will attach this file with the name file.png. -2. Array: ``$email->attachments(['/full/file/path/file.png'])`` will have +2. Array: ``$email->setAttachments(['/full/file/path/file.png'])`` will have the same behavior as using a string. 3. Array with key: - ``$email->attachments(['photo.png' => '/full/some_hash.png'])`` will + ``$email->setAttachments(['photo.png' => '/full/some_hash.png'])`` will attach some_hash.png with the name photo.png. The recipient will see photo.png, not some_hash.png. 4. Nested arrays:: - $email->attachments([ + $email->setAttachments([ 'photo.png' => [ 'file' => '/full/some_hash.png', 'mimetype' => 'image/png', @@ -360,9 +341,6 @@ you want the filenames to appear in the recipient's mail client: a string using the ``data`` option. This allows you to attach files without needing file paths to them. -.. deprecated:: 3.4.0 - Use ``setAttachments()`` instead of ``attachments()``. - Using Transports ================ @@ -375,14 +353,11 @@ method or have the transport in your configuration:: $email = new Email(); // Use a named transport already configured using Email::configTransport() - $email->transport('gmail'); + $email->setTransport('gmail'); // Use a constructed object. $transport = new DebugTransport(); - $email->transport($transport); - -.. deprecated:: 3.4.0 - Use ``setTransport()`` instead of ``transport()``. + $email->setTransport($transport); Creating Custom Transports -------------------------- @@ -431,10 +406,7 @@ necessary when dealing with some ISP's:: // Relax the email pattern, so you can send // to non-conformant addresses. - $email->emailPattern($newPattern); - -.. deprecated:: 3.4.0 - Use ``setEmailPattern()`` instead of ``emailPattern()``. + $email->setEmailPattern($newPattern); Sending Messages Quickly ======================== @@ -475,7 +447,7 @@ When sending emails within a CLI script (Shells, Tasks, ...) you should manually set the domain name for Email to use. It will serve as the host name for the message id (since there is no host name in a CLI environment):: - $email->domain('www.example.org'); + $email->setDomain('www.example.org'); // Results in message ids like ```` (valid) // Instead of ``` (invalid) @@ -503,16 +475,16 @@ following:: public function welcome($user) { $this - ->to($user->email) - ->subject(sprintf('Welcome %s', $user->name)) - ->template('welcome_mail', 'custom'); // By default template with same name as method name is used. + ->setTo($user->email) + ->setSubject(sprintf('Welcome %s', $user->name)) + ->setTemplate('welcome_mail', 'custom'); // By default template with same name as method name is used. } public function resetPassword($user) { $this - ->to($user->email) - ->subject('Reset password') + ->setTo($user->email) + ->setSubject('Reset password') ->setViewVars(['token' => $user->token]); } } diff --git a/en/core-libraries/events.rst b/en/core-libraries/events.rst index fd8700856f..624150eafa 100644 --- a/en/core-libraries/events.rst +++ b/en/core-libraries/events.rst @@ -64,17 +64,13 @@ has been created. To keep your Orders model clean you could use events:: $event = new Event('Model.Order.afterPlace', $this, [ 'order' => $order ]); - $this->eventManager()->dispatch($event); + $this->getEventManager()->dispatch($event); return true; } return false; } } -.. deprecated:: 3.5.0 - Use ``getEventManager()`` instead. - - The above code allows you to notify the other parts of the application that an order has been created. You can then do tasks like send email notifications, update stock, log relevant statistics and other tasks in separate diff --git a/en/core-libraries/registry-objects.rst b/en/core-libraries/registry-objects.rst index 10d0298158..1a46a1e1b1 100644 --- a/en/core-libraries/registry-objects.rst +++ b/en/core-libraries/registry-objects.rst @@ -47,10 +47,10 @@ accomplish this now. For example, you could disable component callbacks in the following way:: // Remove Auth from callbacks. - $this->eventManager()->off($this->Auth); + $this->getEventManager()->off($this->Auth); // Re-enable Auth for callbacks. - $this->eventManager()->on($this->Auth); + $this->getEventManager()->on($this->Auth); .. meta:: :title lang=en: Object Registry diff --git a/en/development/dispatch-filters.rst b/en/development/dispatch-filters.rst deleted file mode 100644 index 2cafa6e7b9..0000000000 --- a/en/development/dispatch-filters.rst +++ /dev/null @@ -1,201 +0,0 @@ -Dispatcher Filters -################## - -.. deprecated:: 3.3.0 - As of 3.3.0 Dispatcher Filters are deprecated. You should use - :doc:`/controllers/middleware` instead now. - -There are several reasons to want a piece of code to be run before any -controller code is executed or right before the response is sent to the client, -such as response caching, header tuning, special authentication or just to -provide access to a mission-critical API response in lesser time than a complete -request dispatching cycle would take. - -CakePHP provides a clean interface for attaching filters to the dispatch -cycle. It is similar to a middleware layer, but re-uses the existing event -subsystem used in other parts of CakePHP. Since they do not work exactly -like traditional middleware, we refer to them as *Dispatcher Filters*. - -Built-in Filters -================ - -CakePHP comes with several dispatcher filters built-in. They handle common -features that all applications are likely to need. The built-in filters are: - -* ``AssetFilter`` checks whether the request is referring to a theme - or plugin asset file, such as a CSS, JavaScript or image file stored in either a - plugin's webroot folder or the corresponding one for a Theme. It will serve the - file accordingly if found, stopping the rest of the dispatching cycle:: - - // Use options to set cacheTime for your static assets - // If not set, this defaults to +1 hour - DispatcherFactory::add('Asset', ['cacheTime' => '+24 hours']); - -* ``RoutingFilter`` applies application routing rules to the request URL. - Populates ``$request->getParam()`` with the results of routing. -* ``ControllerFactory`` uses ``$request->getParam()`` to locate the controller that - will handle the current request. -* ``LocaleSelector`` enables automatic language switching from the ``Accept-Language`` - header sent by the browser. - -Using Filters -============= - -Filters are usually enabled in your application's **bootstrap.php** file, but -you could load them any time before the request is dispatched. Adding -and removing filters is done through :php:class:`Cake\\Routing\\DispatcherFactory`. By -default, the CakePHP application template comes with a couple filter classes -already enabled for all requests; let's take a look at how they are added:: - - DispatcherFactory::add('Routing'); - DispatcherFactory::add('ControllerFactory'); - - // Plugin syntax is also possible - DispatcherFactory::add('PluginName.DispatcherName'); - - // Use options to set priority - DispatcherFactory::add('Asset', ['priority' => 1]); - -Dispatcher filters with higher ``priority`` (lower numbers) - will be executed -first. Priority defaults to ``10``. - -While using the string name is convenient, you can also pass instances into -``add()``:: - - use Cake\Routing\Filter\RoutingFilter; - - DispatcherFactory::add(new RoutingFilter()); - -Configuring Filter Order ------------------------- - -When adding filters, you can control the order they are invoked in using -event handler priorities. While filters can define a default priority using the -``$_priority`` property, you can set a specific priority when attaching the -filter:: - - DispatcherFactory::add('Asset', ['priority' => 1]); - DispatcherFactory::add(new AssetFilter(['priority' => 1])); - -The higher the priority the later this filter will be invoked. - -Conditionally Applying Filters ------------------------------- - -If you don't want to run a filter on every request, you can use conditions to -only apply it some of the time. You can apply conditions using the ``for`` and -``when`` options. The ``for`` option lets you match on URL substrings, while the -``when`` option allows you to run a callable:: - - // Only runs on requests starting with `/blog` - DispatcherFactory::add('BlogHeader', ['for' => '/blog']); - - // Only run on GET requests. - DispatcherFactory::add('Cache', [ - 'when' => function ($request, $response) { - return $request->is('get'); - } - ]); - -The callable provided to ``when`` should return ``true`` when the filter should run. -The callable can expect to get the current request and response as arguments. - -Building a Filter -================= - -To create a filter, define a class in **src/Routing/Filter**. In this example, -we'll be making a filter that adds a tracking cookie for the first landing -page. First, create the file. Its contents should look like:: - - namespace App\Routing\Filter; - - use Cake\Event\Event; - use Cake\Routing\DispatcherFilter; - - class TrackingCookieFilter extends DispatcherFilter - { - - public function beforeDispatch(Event $event) - { - $request = $event->getData('request'); - $response = $event->getData('response'); - if (!$request->getCookie('landing_page')) { - $response->cookie([ - 'name' => 'landing_page', - 'value' => $request->here(), - 'expire' => '+ 1 year', - ]); - } - } - } - -Save this file into **src/Routing/Filter/TrackingCookieFilter.php**. As you can see, like other -classes in CakePHP, dispatcher filters have a few conventions: - -* Class names end in ``Filter``. -* Classes are in the ``Routing\Filter`` namespace. For example, - ``App\Routing\Filter``. -* Generally filters extend ``Cake\Routing\DispatcherFilter``. - -``DispatcherFilter`` exposes two methods that can be overridden in subclasses, -they are ``beforeDispatch()`` and ``afterDispatch()``. These methods are -executed before or after any controller is executed respectively. Both methods -receive a :php:class:`Cake\\Event\\Event` object containing the ``ServerRequest`` and -``Response`` objects (:php:class:`Cake\\Http\\ServerRequest` and -:php:class:`Cake\\Http\\Response` instances) inside the ``$data`` property. - -While our filter was pretty simple, there are a few other interesting things we -can do in filter methods. By returning an ``Response`` object, you can -short-circuit the dispatch process and prevent the controller from being called. -When returning a response, you should also remember to call -``$event->stopPropagation()`` so other filters are not called. - -.. note:: - - When a beforeDispatch method returns a response, the controller, and - afterDispatch event will not be invoked. - -Let's now create another filter for altering response headers in any public -page, in our case it would be anything served from the ``PagesController``:: - - namespace App\Routing\Filter; - - use Cake\Event\Event; - use Cake\Routing\DispatcherFilter; - - class HttpCacheFilter extends DispatcherFilter - { - - public function afterDispatch(Event $event) - { - $request = $event->getData('request'); - $response = $event->getData('response'); - - if ($response->statusCode() === 200) { - $response->sharable(true); - $response->expires(strtotime('+1 day')); - } - } - } - - // In our bootstrap.php - DispatcherFactory::add('HttpCache', ['for' => '/pages']) - -This filter will send a expiration header to 1 day in the future for -all responses produced by the pages controller. You could of course do the same -in the controller, this is just an example of what could be done with filters. -For instance, instead of altering the response, you could cache it using -:php:class:`Cake\\Cache\\Cache` and serve the response from the ``beforeDispatch()`` -callback. - -While powerful, dispatcher filters have the potential to make your application -more difficult to maintain. Filters are an extremely powerful tool when used -wisely and adding response handlers for each URL in your app is not a good use for -them. Keep in mind that not everything needs to be a filter; `Controllers` and -`Components` are usually a more accurate choice for adding any request handling -code to your app. - -.. meta:: - :title lang=en: Dispatcher Filters - :description lang=en: Dispatcher filters are a middleware layer for CakePHP allowing to alter the request or response before it is sent - :keywords lang=en: middleware, filters, dispatcher, request, response, rack, application stack, events, beforeDispatch, afterDispatch, router diff --git a/en/development/routing.rst b/en/development/routing.rst index 46d576b21d..69b659bae1 100644 --- a/en/development/routing.rst +++ b/en/development/routing.rst @@ -1522,12 +1522,6 @@ This will populate ``$this->request->getParam('named')`` with any named paramete found in the passed arguments. Any passed argument that was interpreted as a named parameter, will be removed from the list of passed arguments. -.. toctree:: - :glob: - :maxdepth: 1 - - /development/dispatch-filters - .. meta:: :title lang=en: Routing :keywords lang=en: controller actions,default routes,mod rewrite,code index,string url,php class,incoming requests,dispatcher,url url,meth,maps,match,parameters,array,config,cakephp,apache,router diff --git a/en/development/testing.rst b/en/development/testing.rst index d07cc13838..efcce75f7f 100644 --- a/en/development/testing.rst +++ b/en/development/testing.rst @@ -1537,7 +1537,7 @@ Expanding on the Orders example, say we have the following tables:: $event = new Event('Model.Order.afterPlace', $this, [ 'order' => $order ]); - $this->eventManager()->dispatch($event); + $this->getEventManager()->dispatch($event); return true; } return false; diff --git a/en/epub-contents.rst b/en/epub-contents.rst index b3081f5421..a8ac806b0b 100644 --- a/en/epub-contents.rst +++ b/en/epub-contents.rst @@ -8,7 +8,7 @@ Contents intro quickstart - appendices/3-0-migration-guide + appendices/4-0-migration-guide tutorials-and-examples contributing diff --git a/en/orm/query-builder.rst b/en/orm/query-builder.rst index 8c57f70a74..8f3858c8ae 100644 --- a/en/orm/query-builder.rst +++ b/en/orm/query-builder.rst @@ -659,12 +659,6 @@ methods being combined with ``AND``. The resulting SQL would look like:: AND spam != 1 AND view_count > 10) -.. deprecated:: 3.5.0 - As of 3.5.0 the ``orWhere()`` method is deprecated. This method creates - hard to predict SQL based on the current query state. - Use ``where()`` instead as it has more predictable and easier - to understand behavior. - However, if we wanted to use both ``AND`` & ``OR`` conditions we could do the following:: diff --git a/en/orm/saving-data.rst b/en/orm/saving-data.rst index 99a97e9c6d..744629d92f 100644 --- a/en/orm/saving-data.rst +++ b/en/orm/saving-data.rst @@ -656,7 +656,7 @@ data into an entity:: // Only allow title to be changed $entity = $this->patchEntity($entity, $data, [ - 'fieldList' => ['title'] + 'fields' => ['title'] ]); $this->save($entity); @@ -665,7 +665,7 @@ You can also control which properties can be assigned for associations:: // Only allow changing the title and tags // and the tag name is the only column that can be set $entity = $this->patchEntity($entity, $data, [ - 'fieldList' => ['title', 'tags'], + 'fields' => ['title', 'tags'], 'associated' => ['Tags' => ['fieldList' => ['name']]] ]); $this->save($entity); @@ -674,12 +674,6 @@ Using this feature is handy when you have many different functions your users can access and you want to let your users edit different data based on their privileges. -The ``fieldList`` options is also accepted by the ``newEntity()``, -``newEntities()`` and ``patchEntities()`` methods. - -.. deprecated:: 3.4.0 - Use ``fields`` instead of ``fieldList``. - .. _saving-entities: Saving Entities diff --git a/en/orm/validation.rst b/en/orm/validation.rst index de86848ceb..10e5ade6a5 100644 --- a/en/orm/validation.rst +++ b/en/orm/validation.rst @@ -243,12 +243,9 @@ Getting Validators From Tables Once you have created a few validation sets in your table class, you can get the resulting object by name:: - $defaultValidator = $usersTable->validator('default'); + $defaultValidator = $usersTable->getValidator('default'); - $hardenedValidator = $usersTable->validator('hardened'); - -.. deprecated:: 3.5.0 - ``validator()`` is deprecated. Use ``getValidator()`` instead. + $hardenedValidator = $usersTable->getValidator('hardened'); Default Validator Class ======================= diff --git a/en/pdf-contents.rst b/en/pdf-contents.rst index 6660a58804..187fb362c1 100644 --- a/en/pdf-contents.rst +++ b/en/pdf-contents.rst @@ -8,7 +8,7 @@ Contents intro quickstart - appendices/3-0-migration-guide + appendices/4-0-migration-guide tutorials-and-examples contributing diff --git a/en/plugins.rst b/en/plugins.rst index 161b825a1f..79b1539175 100644 --- a/en/plugins.rst +++ b/en/plugins.rst @@ -91,18 +91,6 @@ Additionally, you will need to tell Composer to refresh its autoloading cache: php composer.phar dumpautoload -If you are unable to use Composer for any reason, you can also configure -autoloading with ``Plugin``:: - - Plugin::load('ContactManager', ['autoload' => true]); - - -.. deprecated:: 3.7.0 - Plugin::load() and ``autoload`` option are deprecated. - -.. note:: - IMPORTANT: ``autoload`` option is not available on ``addPlugin()``, you should use ``composer dumpautoload`` instead. - Loading a Plugin ================ diff --git a/en/security.rst b/en/security.rst index 007fd1c27c..12b9511978 100644 --- a/en/security.rst +++ b/en/security.rst @@ -8,8 +8,8 @@ The following sections cover those tools: :maxdepth: 1 core-libraries/security - controllers/components/csrf Security Component + CSRF Middleware .. meta:: :title lang=en: Security diff --git a/en/views/helpers.rst b/en/views/helpers.rst index 92ca010e65..9890b49606 100644 --- a/en/views/helpers.rst +++ b/en/views/helpers.rst @@ -21,8 +21,6 @@ helpers included in CakePHP, check out the chapter for each helper: /views/helpers/html /views/helpers/number /views/helpers/paginator - /views/helpers/rss - /views/helpers/session /views/helpers/text /views/helpers/time /views/helpers/url diff --git a/en/views/helpers/rss.rst b/en/views/helpers/rss.rst deleted file mode 100644 index 5803745f47..0000000000 --- a/en/views/helpers/rss.rst +++ /dev/null @@ -1,202 +0,0 @@ -Rss -### - -.. php:namespace:: Cake\View\Helper - -.. php:class:: RssHelper(View $view, array $config = []) - -The RssHelper makes generating XML for `RSS feeds `_ easy. - -.. deprecated:: 3.5.0 - RssHelper is deprecated as of 3.5.0, and will be removed in 4.0.0 - -Creating an RSS Feed with the RssHelper -======================================= - -This example assumes you have a Articles Controller, Articles Table and an -Article Entity already created and want to make an alternative view for RSS. - -Creating an XML/RSS version of ``articles/index`` is a snap with CakePHP. -After a few simple steps you can simply append the desired extension .rss to -``articles/index`` making your URL ``articles/index.rss``. Before we jump too -far ahead trying to get our webservice up and running we need to do a few -things. First extensions parsing needs to be activated, this is done in -**config/routes.php**:: - - Router::extensions('rss'); - -In the call above we've activated the .rss extension. When using -:php:meth:`Cake\\Routing\\Router::extensions()` you can pass a string or an -array of extensions as first argument. This will activate each -extension/content-type for use in your application. Now when the address -``articles/index.rss`` is requested you will get an XML version of -your ``articles/index``. However, first we need to edit the controller to -add in the rss-specific code. - -Controller Code ---------------- - -It is a good idea to add RequestHandler to your ArticlesController's -``initialize()`` method. This will allow a lot of automagic to occur:: - - public function initialize() - { - parent::initialize(); - $this->loadComponent('RequestHandler'); - } - -Before we can make an RSS version of our ``articles/index`` we need to get a few -things in order. It may be tempting to put the channel metadata in the -controller action and pass it to your view using the -:php:meth:`Cake\\Controller\\Controller::set()` method but this is -inappropriate. That information can also go in the view. That will come later -though, for now if you have a different set of logic for the data used to make -the RSS feed and the data for the HTML view you can use the -:php:meth:`Cake\\Controller\\Component\\RequestHandler::isRss()` method, -otherwise your controller can stay the same:: - - // Modify the Posts Controller action that corresponds to - // the action which deliver the rss feed, which is the - // Index action in our example. - - public function index() - { - if ($this->RequestHandler->isRss() ) { - $articles = $this->Articles - ->find() - ->limit(20) - ->order(['created' => 'desc']); - $this->set(compact('articles')); - } else { - // this is not an Rss request, so deliver - // data used by website's interface. - $this->paginate = [ - 'order' => ['created' => 'desc'], - 'limit' => 10 - ]; - $this->set('articles', $this->paginate($this->Articles)); - $this->set('_serialize', ['articles']); - } - } - -With all the View variables set we need to create an rss layout. - -Layout ------- - -An Rss layout is very simple, put the following contents in -**templates/Layout/rss/default.php**:: - - if (!isset($documentData)) { - $documentData = []; - } - if (!isset($channelData)) { - $channelData = []; - } - if (!isset($channelData['title'])) { - $channelData['title'] = $this->fetch('title'); - } - $channel = $this->Rss->channel([], $channelData, $this->fetch('content')); - echo $this->Rss->document($documentData, $channel); - -It doesn't look like much but thanks to the power in the ``RssHelper`` -it's doing a lot of lifting for us. We haven't set ``$documentData`` or -``$channelData`` in the controller, however in CakePHP your views -can pass variables back to the layout. Which is where our ``$channelData`` -array will come from setting all of the meta data for our feed. - -Next up is view file for my articles/index. Much like the layout file -we created, we need to create a **templates/Posts/rss/** directory and -create a new **index.php** inside that folder. The contents of the file -are below. - -View ----- - -Our view, located at **templates/Posts/rss/index.php**, begins by setting the -``$documentData`` and ``$channelData`` variables for the layout, these contain -all the metadata for our RSS feed. This is done by using the -:php:meth:`Cake\\View\\View::set()` method which is analogous to the -:php:meth:`Cake\\Controller\\Controller::set()` method. Here though we are -passing the channel's metadata back to the layout:: - - $this->set('channelData', [ - 'title' => __("Most Recent Posts"), - 'link' => $this->Url->build('/', true), - 'description' => __("Most recent posts."), - 'language' => 'en-us' - ]); - -The second part of the view generates the elements for the actual records of -the feed. This is accomplished by looping through the data that has been passed -to the view ($items) and using the :php:meth:`RssHelper::item()` method. The -other method you can use, :php:meth:`RssHelper::items()` which takes a callback -and an array of items for the feed. The callback method is usually called -``transformRss()``. There is one downfall to this method, which is that you -cannot use any of the other helper classes to prepare your data inside the -callback method because the scope inside the method does not include anything -that is not passed inside, thus not giving access to the TimeHelper or any -other helper that you may need. The :php:meth:`RssHelper::item()` transforms -the associative array into an element for each key value pair. - -.. note:: - - You will need to modify the $link variable as appropriate to - your application. You might also want to use a - :ref:`virtual field ` in your Entity. - -:: - - foreach ($articles as $article) { - $created = strtotime($article->created); - - $link = [ - 'controller' => 'Articles', - 'action' => 'view', - 'year' => date('Y', $created), - 'month' => date('m', $created), - 'day' => date('d', $created), - 'slug' => $article->slug - ]; - - // Remove & escape any HTML to make sure the feed content will validate. - $body = h(strip_tags($article->body)); - $body = $this->Text->truncate($body, 400, [ - 'ending' => '...', - 'exact' => true, - 'html' => true, - ]); - - echo $this->Rss->item([], [ - 'title' => $article->title, - 'link' => $link, - 'guid' => ['url' => $link, 'isPermaLink' => 'true'], - 'description' => $body, - 'pubDate' => $article->created - ]); - } - -You can see above that we can use the loop to prepare the data to be transformed -into XML elements. It is important to filter out any non-plain text characters -out of the description, especially if you are using a rich text editor for the -body of your blog. In the code above we used ``strip_tags()`` and -:php:func:`h()` to remove/escape any XML special characters from the content, -as they could cause validation errors. Once we have set up the data for the -feed, we can then use the :php:meth:`RssHelper::item()` method to create the XML -in RSS format. Once you have all this setup, you can test your RSS feed by going -to your site ``/posts/index.rss`` and you will see your new feed. It is always -important that you validate your RSS feed before making it live. This can be -done by visiting sites that validate the XML such as Feed Validator or the w3c -site at http://validator.w3.org/feed/. - -.. note:: - - You may need to set the value of 'debug' in your core configuration - to ``false`` to get a valid feed, because of the various debug - information added automagically under higher debug settings that - break XML syntax or feed validation rules. - -.. meta:: - :title lang=en: RssHelper - :description lang=en: The RssHelper makes generating XML for RSS feeds easy. - :keywords lang=en: rss helper,rss feed,isrss,rss item,channel data,document data,parse extensions,request handler diff --git a/en/views/helpers/session.rst b/en/views/helpers/session.rst deleted file mode 100644 index f1579f99aa..0000000000 --- a/en/views/helpers/session.rst +++ /dev/null @@ -1,50 +0,0 @@ -Session -####### - -.. php:namespace:: Cake\View\Helper - -.. php:class:: SessionHelper(View $view, array $config = []) - -.. deprecated:: 3.0.0 - The SessionHelper is deprecated in 3.x. Instead you should use either the - :doc:`FlashHelper ` or :ref:`access the - session via the request `. - -As a natural counterpart to the Session object, the Session -Helper replicates most of the object's functionality and makes it -available in your view. - -The major difference between the SessionHelper and the Session -object is that the helper does *not* have the ability to write -to the session. - -As with the session object, data is read by using -:term:`dot notation` array structures:: - - ['User' => [ - 'username' => 'super@example.com' - ]]; - -Given the previous array structure, the node would be accessed by -``User.username``, with the dot indicating the nested array. This -notation is used for all SessionHelper methods wherever a ``$key`` is -used. - -.. php:method:: read(string $key) - - :rtype: mixed - - Read from the Session. Returns a string or array depending on the - contents of the session. - -.. php:method:: check(string $key) - - :rtype: boolean - - Check to see whether a key is in the Session. Returns a boolean representing the - key's existence. - -.. meta:: - :title lang=en: SessionHelper - :description lang=en: The SessionHelper replicates most of the functionality and making it available in your view. - :keywords lang=en: session helper,flash messages,session flash,session read,session check