3.5 Migration Guide

CakePHP 3.5 is an API compatible upgrade from 3.4. This page outlines thechanges and improvements made in 3.5.

To upgrade to 3.5.x run the following composer command:

  1. php composer.phar require --update-with-dependencies "cakephp/cakephp:3.5.*"

Deprecations

The following is a list of deprecated methods, properties and behaviors. Thesefeatures will continue to function until 4.0.0 after which they will be removed.

  • Cake\Http\Client\CookieCollection is deprecated. UseCake\Http\Cookie\CookieCollection instead.
  • Cake\View\Helper\RssHelper is deprecated. Due to infrequent use theRssHelper is deprecated.
  • Cake\Controller\Component\CsrfComponent is deprecated. UseCross Site Request Forgery (CSRF) Middleware instead.
  • Cake\Datasource\TableSchemaInterface is deprecated. UseCake\Database\TableSchemaAwareInterface instead.
  • Cake\Console\ShellDispatcher is deprecated. Applications should update touse Cake\Console\CommandRunner instead.
  • Cake\Database\Schema\TableSchema::column() is deprecated. UseCake\Database\Schema\TableSchema::getColumn() instead.
  • Cake\Database\Schema\TableSchema::constraint() is deprecated. UseCake\Database\Schema\TableSchema::getConstraint() instead.
  • Cake\Database\Schema\TableSchema::index() is deprecated. UseCake\Database\Schema\TableSchema::getIndex() instead.

Deprecated Combined Get/Set Methods

In the past CakePHP has leveraged ‘modal’ methods that provide botha get and set mode. These methods complicate IDE autocompletion and our abilityto add stricter return types in the future. For these reasons, combined get/setmethods are being split into separate get and set methods.

The following is a list of methods that are deprecated and replaced withgetX() and setX() methods:

  • Cake\Cache\Cache
    • config()
    • registry()
  • Cake\Console\Shell
    • io()
  • Cake\Console\ConsoleIo
    • outputAs()
  • Cake\Console\ConsoleOutput
    • outputAs()
  • Cake\Database\Connection
    • logger()
  • Cake\Database\TypedResultInterface
    • returnType()
  • Cake\Database\TypedResultTrait
    • returnType()
  • Cake\Database\Log\LoggingStatement
    • logger()
  • Cake\Datasource\ModelAwareTrait
    • modelType()
  • Cake\Database\Query
    • getter part of valueBinder() (now getValueBinder())
  • Cake\Database\Schema\TableSchema
    • columnType()
  • Cake\Datasource\QueryTrait
    • getter part of eagerLoaded() (now isEagerLoaded())
  • Cake\Event\EventDispatcherInterface
    • eventManager()
  • Cake\Event\EventDispatcherTrait
    • eventManager()
  • Cake\Error\Debugger
    • outputAs() (now getOutputFormat() / setOutputFormat())
  • Cake\Http\ServerRequest
    • env() (now getEnv() / withEnv())
    • charset() (now getCharset() / withCharset())
  • Cake\I18n\I18n
    • locale()
    • translator()
    • defaultLocale()
    • defaultFormatter()
  • Cake\ORM\Association\BelongsToMany
    • sort()
  • Cake\ORM\LocatorAwareTrait
    • tableLocator()
  • Cake\ORM\EntityTrait
    • invalid() (now getInvalid(), setInvalid(),setInvalidField(), and getInvalidField())
  • Cake\ORM\Table
    • validator()
  • Cake\Routing\RouteBuilder
    • extensions()
    • routeClass()
  • Cake\Routing\RouteCollection
    • extensions()
  • Cake\TestSuite\TestFixture
    • schema()
  • Cake\Utility\Security
    • salt()
  • Cake\View\View
    • template()
    • layout()
    • theme()
    • templatePath()
    • layoutPath()
    • autoLayout() (now isAutoLayoutEnabled() / enableAutoLayout())

Behavior Changes

While these changes are API compatible, they represent minor variances inbehavior that may affect your application:

  • BehaviorRegistry, HelperRegistry and ComponentRegistry will nowraise exceptions when unload() is called with an unknown object name. Thischange should help find errors easier by making possible typos more visible.
  • HasMany associations now gracefully handle empty values set for theassociation property, similar to BelongsToMany associations - that is theytreat false, null, and empty strings the same way as empty arrays. ForHasMany associations this now results in all associated records to bedeleted/unlinked when the replace save strategy is being used.As a result this allows you to use forms to delete/unlink all associatedrecords by passing an empty string. Previously this would have required custommarshalling logic.
  • ORM\Table::newEntity() now only marks association properties dirty if themarshalled association record is dirty. In scenarios where an associationentity is created that contains no properties the empty record will not beflagged for persistence.
  • Http\Client no longer uses the cookie() method results when buildingrequests. Instead the Cookie header and internal CookieCollection areused. This should only effect applications that have a custom HTTP adapter intheir clients.
  • Multi-word subcommand names previouly required camelBacked names to be usedwhen invoking shells. Now subcommands can be invoked with underscored_names.For example: cake tool initMyDb can now be called with cake tool
    init_my_db
    . If your shells previously bound two subcommands with differentinflections, only the last bound command will function.
  • SecurityComponent will blackhole post requests that have no request datanow. This change helps protect actions that create records using databasedefaults alone.
  • Cake\ORM\Table::addBehavior() and removeBehavior() now return$this to assist in defining table objects in a fluent fashion.
  • Cache engines no longer throw an exception when they fail or are misconfigured,but instead fall back to the noop NullEngine. Fallbacks can also beconfigured on a per-engine basis.
  • Cake\Database\Type\DateTimeType will now marshal ISO-8859-1 formatteddatetime strings (e.g. 2017-07-09T12:33:00+00:02) in addition to thepreviously accepted format. If you have a subclass of DateTimeType you mayneed to update your code.

New Features

Scoped Middleware

Middleware can now be conditionally applied to routes in specific URLscopes. This allows you to build specific stacks of middleware for differentparts of your application without having to write URL checking code in yourmiddleware. See the Connecting Scoped Middleware section for moreinformation.

New Console Runner

3.5.0 adds Cake\Console\CommandRunner. This class alongsideCake\Console\CommandCollection integrate the CLI environment with the newApplication 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 newclass requires replacing the contents of your bin/cake.php file with thefollowing file.

Cache Engine Fallbacks

Cache engines can now be configured with a fallback key that defines acache configuration to fall back to if the engine is misconfigured (orunavailable). See Configuring Cache Fallbacks for more information onconfiguring fallbacks.

dotenv Support added to Application Skeleton

The application skeleton now features a ‘dotenv’ integration making it easier touse environment variables to configure your application. See theEnvironment Variables section for more information.

Console Integration Testing

The Cake\TestSuite\ConsoleIntegrationTestCase class was added to makeintegration testing console applications easier. For more information, visitthe Testing Commands section. This test class is fullycompatible with the current Cake\Console\ShellDispatcher as well as the newCake\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 keydoes not exist.
  • Cake\Core\ObjectRegistry now implements the Countable andIteratorAggregate interfaces.

Console

  • Cake\Console\ConsoleOptionParser::setHelpAlias() was added. This methodallows you to set the command name used when generating help output. Defaultsto cake.
  • Cake\Console\CommandRunnner was added replacingCake\Console\ShellDispatcher.
  • Cake\Console\CommandCollection was added to provide an interface forapplications to define the command line tools they offer.

Database

  • SQLite driver had the mask option added. This option lets you set thefile 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 thesenew abstract types. TINYINT(1) columns will continue to be treated asboolean columns in MySQL.
  • Cake\Datasource\PaginatorInterface was added. The PaginatorComponentnow uses this interface to interact with paginators. This allows otherORM-like implementations to be paginated by the component.
  • Cake\Datasource\Paginator was added to paginate ORM/Database Queryinstances.

Event

  • Cake\Event\EventManager::on() and off() methods are now chainablemaking it simpler to set multiple events at once.

Http

  • New Cookie & CookieCollection classes have been added. These classes allow youto work with cookies in an object-orientated way, and are available onCake\Http\ServerRequest, Cake\Http\Response, andCake\Http\Client\Response. See the Cookies andSetting Cookies for more information.
  • New middleware has been added to make applying security headers easier. SeeSecurity Header Middleware for more information.
  • New middleware has been added to transparently encrypt cookie data. SeeEncrypted Cookie Middleware for more information.
  • New middleware has been added to make protecting against CSRF easier. SeeCross Site Request Forgery (CSRF) Middleware for more information.
  • Cake\Http\Client::addCookie() was added to make it easy to add cookies toa client instance.

InstanceConfigTrait

  • InstanceConfigTrait::getConfig() now takes a 2nd parameter $default.If no value is available for the specified $key, the $default valuewill be returned.

ORM

  • Cake\ORM\Query::contain() now allows you to call it without the wrappingarray when containing a single association. contain('Comments', function ()
    { … });
    will now work. This makes contain() consistent with othereagerloading related methods like leftJoinWith() and matching().

Routing

  • Cake\Routing\Router::reverseToArray() was added. This method allow you toconvert a request object into an array that can be used to generate URLstrings.
  • Cake\Routing\RouteBuilder::resources() had the path optionadded. This option lets you make the resource path and controller name notmatch.
  • Cake\Routing\RouteBuilder now has methods to create routes forspecific 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 areprovided.
  • IntegrationTestCase::head() was added.
  • IntegrationTestCase::options() was added.
  • IntegrationTestCase::disableErrorHandlerMiddleware() was added to makedebugging errors easier in integration tests.

Validation

  • Cake\Validation\Validator::scalar() was added to ensure that fields do notget non-scalar data.
  • Cake\Validation\Validator::regex() was added for a more convenient wayto validate data against a regex pattern.
  • Cake\Validation\Validator::addDefaultProvider() was added. This methodlets you inject validation providers into all the validators created in yourapplication.
  • Cake\Validation\ValidatorAwareInterface was added to define the methodsimplemented by Cake\Validation\ValidatorAwareTrait.

View

  • Cake\View\Helper\PaginatorHelper::limitControl() was added. This methodlets you create a form with a select box for updating the limit value ona paginated result set.