40 KiB
Upgrading Instructions for Yii Framework 2.0
This file contains the upgrade notes for Yii 2.0. These notes highlight changes that could break your application when you upgrade Yii from one version to another. Even though we try to ensure backwards compabitilty (BC) as much as possible, sometimes it is not possible or very complicated to avoid it and still create a good solution to a problem. You may also want to check out the versioning policy for further details.
Upgrading in general is as simple as updating your dependency in your composer.json and
running composer update. In a big application however there may be more things to consider,
which are explained in the following.
Note: This document assumes you have composer installed globally so that you can run the
composercommand. If you have acomposer.pharfile inside of your project you need to replacecomposerwithphp composer.pharin the following.
Tip: Upgrading dependencies of a complex software project always comes at the risk of breaking something, so make sure you have a backup (you should be doing this anyway ;) ).
In case you use composer asset plugin instead of the currently recommended asset-packagist.org to install Bower and NPM assets, make sure it is upgraded to the latest version as well. To ensure best stability you should also upgrade composer in this step:
composer self-update
composer global require "fxp/composer-asset-plugin:^1.4.1" --no-plugins
The simple way to upgrade Yii, for example to version 2.0.10 (replace this with the version you want) will be running composer require:
composer require "yiisoft/yii2:~2.0.10" --update-with-dependencies
This command will only upgrade Yii and its direct dependencies, if necessary. Without --update-with-dependencies the
upgrade might fail when the Yii version you chose has slightly different dependencies than the version you had before.
composer require will by default not update any other packages as a safety feature.
Another way to upgrade is to change the composer.json file to require the new Yii version and then
run composer update by specifying all packages that are allowed to be updated.
composer update yiisoft/yii2 yiisoft/yii2-composer bower-asset/inputmask
The above command will only update the specified packages and leave the versions of all other dependencies intact.
This helps to update packages step by step without causing a lot of package version changes that might break in some way.
If you feel lucky you can of course update everything to the latest version by running composer update without
any restrictions.
After upgrading you should check whether your application still works as expected and no tests are broken. See the following notes on which changes to consider when upgrading from one version to another.
Note: The following upgrading instructions are cumulative. That is, if you want to upgrade from version A to version C and there is version B between A and C, you need to follow the instructions for both A and B.
Upgrade from Yii 2.0.15
-
Updated dependency to
cebe/markdownto version1.2.x. If you need stick with 1.1.x, you can specify that in yourcomposer.jsonby adding the following line in therequiresection:"cebe/markdown": "~1.1.0", -
yii\mutex\Mutex::acquire()no longer returnstrueif lock is already acquired by the same component in the same process. Make sure that you're not trying to acquire the same lock multiple times in a way that may create infinite loops, for example:if (Yii::$app->mutex->acquire('test')) { while (!Yii::$app->mutex->acquire('test')) { // `Yii::$app->mutex->acquire('test')` will always return `false` here, since lock is already acquired } }
Upgrade from Yii 2.0.14
-
When hash format condition (array) is used in
yii\db\ActiveRecord::findOne()andfindAll(), the array keys (column names) are now limited to the table column names. This is to prevent SQL injection if input was not filtered properly. You should check all usages offindOne()andfindAll()to ensure that input is filtered correctly. If you need to find models using different keys than the table columns, usefind()->where(...)instead.It's not an issue in the default generated code though as ID is filtered by controller code:
The following code examples are not affected by this issue (examples shown for
findOne()are valid also forfindAll()):// yii\web\Controller ensures that $id is scalar public function actionView($id) { $model = Post::findOne($id); // ... }// casting to (int) or (string) ensures no array can be injected (an exception will be thrown so this is not a good practise) $model = Post::findOne((int) Yii::$app->request->get('id'));// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record $model = Post::findOne(['id' => Yii::$app->request->get('id')]);The following code however is vulnerable, an attacker could inject an array with an arbitrary condition and even exploit SQL injection:
$model = Post::findOne(Yii::$app->request->get('id'));For the above example, the SQL injection part is fixed with the patches provided in this release, but an attacker may still be able to search records by different condition than a primary key search and violate your application business logic. So passing user input directly like this can cause problems and should be avoided.
Upgrade from Yii 2.0.13
-
Constants
IPV6_ADDRESS_LENGTH,IPV4_ADDRESS_LENGTHwere moved fromyii\validators\IpValidatortoyii\helpers\IpHelper. If your application relies on these constants, make sure to update your code to follow the changes. -
yii\base\Security::compareString()is now throwingyii\base\InvalidArgumentExceptionin case non-strings are compared. -
yii\db\ExpressionInterfacehas been introduced to represent a wider range of SQL expressions. In case you check forinstanceof yii\db\Expressionin your code, you might consider changing that to checking for the interface and use the newly introduced methods to retrieve the expression content. -
Added JSON support for PostgreSQL and MySQL as well as Arrays support for PostgreSQL in ActiveRecord layer. In case you already implemented such support yourself, please switch to Yii implementation.
- For MySQL JSON and PgSQL JSON & JSONB columns Active Record will return decoded JSON (that can be either array or scalar) after data population and expects arrays or scalars to be assigned for further saving them into a database.
- For PgSQL Array columns Active Record will return
yii\db\ArrayExpressionobject that acts as an array (it implementsArrayAccess,TraversableandCountableinterfaces) and expects array oryii\db\ArrayExpressionto be assigned for further saving it into the database.
In case this change makes the upgrade process to Yii 2.0.14 too hard in your project, you can switch off the described behavior Then you can take your time to change your code and then re-enable arrays or JSON support.
-
yii\db\PdoValueclass has been introduced to replace a special syntax that was used to declare PDO parameter type when binding parameters to an SQL command, for example:['value', \PDO::PARAM_STR]. You should usenew PdoValue('value', \PDO::PARAM_STR)instead. Old syntax will be removed in Yii 2.1. -
yii\db\QueryBuilder::conditionBuildersproperty and method-based condition builders are no longer used. Class-based conditions and builders are introduced instead to provide more flexibility, extensibility and space to customization. In case you rely on that property or override any of default condition builders, follow the special guide article to update your code. -
Protected method
yii\db\ActiveQueryTrait::createModels()does not apply indexes as defined inindexByproperty anymore.
In case you override default ActiveQuery implementation and relied on that behavior, callyii\db\Query::populate()method instead to index query results according to theindexByparameter. -
Log targets (like
yii\log\EmailTarget) are now throwingyii\log\LogRuntimeExceptionin case log can not be properly exported. -
You can start preparing your application for Yii 2.1 by doing the following:
- Replace
::className()calls with::class(if you’re running PHP 5.5+). - Replace usages of
yii\base\InvalidParamExceptionwithyii\base\InvalidArgumentException. - Replace calls to
Yii::trace()withYii::debug(). - Remove calls to
yii\BaseYii::powered(). - If you are using XCache or Zend data cache, those are going away in 2.1 so you might want to start looking for an alternative.
- Replace
-
In case you aren't using CSRF cookies (REST APIs etc.) you should turn them off explicitly by setting
\yii\web\Request::$enableCsrfCookietofalsein your config file.
Upgrade from Yii 2.0.12
-
The
yii\web\Requestclass allowed to determine the value ofgetIsSecureConnection()form theX-Forwarded-Protoheader if the connection was made via a normal HTTP request. This behavior was insecure as the header could have been set by a malicious client on a non-HTTPS connection. With 2.0.13 Yii adds support for configuring trusted proxies. If your application runs behind a reverse proxy and relies ongetIsSecureConnection()to return the value form theX-Forwarded-Protoheader you need to explicitly allow this in the Request configuration. See the guide for more information.This setting also affects you when Yii is running on IIS webserver, which sets the
X-Rewrite-Urlheader. This header is now filtered by default and must be listed in trusted hosts to be detected by Yii:[ // accept X-Rewrite-Url from all hosts, as it will be set by IIS '/.*/' => ['X-Rewrite-Url'], ] -
For compatibiliy with PHP 7.2 which does not allow classes to be named
Objectanymore, we needed to renameyii\base\Objecttoyii\base\BaseObject.yii\base\Objectstill exists for backwards compatibility and will be loaded if needed in projects that are running on PHP <7.2. The compatibility classyii\base\Objectextends fromyii\base\BaseObjectso if you have classes that extend fromyii\base\Objectthese would still work.What does not work however will be code that relies on
instanceofchecks oris_subclass_of()calls foryii\base\Objecton framework classes as these do not extendyii\base\Objectanymore but only extend fromyii\base\BaseObject. In general such a check is not needed as there is ayii\base\Configurableinterface you should check against instead.Here is a visualisation of the change (
a < bmeans "b extends a"):Before: yii\base\Object < Framework Classes yii\base\Object < Application Classes After Upgrade: yii\base\BaseObject < Framework Classes yii\base\BaseObject < yii\base\Object < Application ClassesIf you want to upgrade PHP to version 7.2 in your project you need to remove all cases that extend
yii\base\Objectand extend fromyii\base\BaseObjectinstead:yii\base\BaseObject < Framework Classes yii\base\BaseObject < Application ClassesFor extensions that have classes extending from
yii\base\Object, to be compatible with PHP 7.2, you need to require"yiisoft/yii2": "~2.0.13"in composer.json and change affected classes to extend fromyii\base\BaseObjectinstead. It is not possible to allow Yii versions<2.0.13and be compatible with PHP 7.2 or higher. -
A new method
public static function instance($refresh = false);has been added to theyii\db\ActiveRecordInterfacevia a newyii\base\StaticInstanceInterface. This change may affect your application in the following ways:- If you have an
instance()method defined in anActiveRecordorModelclass, you need to check whether the behavior is compatible with the method added by Yii. - Otherwise this method is implemented in the
yii\base\Model, so the change only affects your code if you implementActiveRecordInterfacein a class that does not extendModel. You may useyii\base\StaticInstanceTraitto implement it.
- If you have an
-
Fixed built-in validator creating when model has a method with the same name.
It is documented, that for the validation rules declared in model by
yii\base\Model::rules(), validator can be either a built-in validator name, a method name of the model class, an anonymous function, or a validator class name. Before this change behavior was inconsistent with the documentation: method in the model had higher priority, than a built-in validator. In case you have relied on this behavior, make sure to fix it. -
Behavior was changed for methods
yii\base\Module::get()andyii\base\Module::has()so in case when the requested component was not found in the current module, the parent ones will be checked for this component hierarchically. Considering that the root parent module is usually an application, this change can reduce calls to globalYii::$app->get(), and replace them with module-scope calls toget(), making code more reliable and easier to test. However, this change may affect your application if you have code that uses methodyii\base\Module::has()in order to check existence of the component exactly in this specific module. In this case make sure the logic is not corrupted. -
If you are using "asset" command to compress assets and your web application
assetManagerhaslinkAssetsturned on, make sure that "asset" command config haslinkAssetsturned on as well.
Upgrade from Yii 2.0.11
-
yii\i18n\Formatter::normalizeDatetimeValue()returns now array with additional third boolean element indicating whether the timestamp has date information or it is just time value. -
yii\grid\DataColumnfilter is now automatically generated as dropdown list with localizedYesandNostrings in case offormatbeing set toboolean. -
The signature of
yii\db\QueryBuilder::prepareInsertSelectSubQuery()was changed. The method has got an extra optional parameter$params. -
The signature of
yii\cache\Cache::getOrSet()has been adjusted to also accept a callable and not onlyClosure. If you extend this method, make sure to adjust your code. -
yii\web\UrlManagernow checks if rules implementgetCreateUrlStatus()method in order to decide whether to use internal cache forcreateUrl()calls. Ensure that all your custom rules implement this method in order to fully benefit from the acceleration provided by this cache. -
yii\filters\AccessControlnow can be used withoutusercomponent. This has two consequences:- If used without user component,
yii\filters\AccessControl::denyAccess()throwsyii\web\ForbiddenHttpExceptioninstead of redirecting to login page. - If used without user component, using
AccessRulematching a role throwsyii\base\InvalidConfigException.
- If used without user component,
-
Inputmask package name was changed from
jquery.inputmasktoinputmask. If you've configured path to assets manually, please adjust it.
Upgrade from Yii 2.0.10
-
A new method
public function emulateExecution($value = true);has been added to theyii\db\QueryInterace. This method is implemented in theyii\db\QueryTrait, so this only affects your code if you implement QueryInterface in a class that does not use the trait. -
yii\validators\FileValidator::getClientOptions()andyii\validators\ImageValidator::getClientOptions()are now public. If you extend from these classes and override these methods, you must make them public as well. -
yii\widgets\MaskedInputinputmask dependency was updated to~3.3.3. See its changelog for details. -
PJAX: Auto generated IDs of the Pjax widget have been changed to use their own prefix to avoid conflicts. Auto generated IDs are now prefixed with
pinstead ofw. This is defined by the$autoIdPrefixproperty ofyii\widgets\Pjax. If you have any PHP or Javascript code that depends on autogenerated IDs you should update these to match this new value. It is not a good idea to rely on auto generated values anyway, so you better fix these cases by specifying an explicit ID.
Upgrade from Yii 2.0.9
-
RBAC:
getChildRoles()method was added to\yii\rbac\ManagerInterface. If you've implemented your own RBAC manager you need to implement new method. -
Microsoft SQL
NTEXTdata type was marked as deprecated in MSSQL so\yii\db\mssql\Schema::TYPE_TEXTwas changed from'ntext'to `'nvarchar(max)' -
Method
yii\web\Request::getBodyParams()has been changed to pass full value of 'content-type' header to the second argument ofyii\web\RequestParserInterface::parse(). If you create your own custom parser, which relies on$contentTypeargument, ensure to process it correctly as it may content additional data. -
yii\rest\Serializerhas been changed to return a JSON array for collection data in all cases to be consistent among pages for data that is not indexed starting by 0. If your API relies on the Serializer to return data as JSON objects indexed by PHP array keys, you should setyii\rest\Serializer::$preserveKeystotrue.
Upgrade from Yii 2.0.8
-
Part of code from
yii\web\User::loginByCookie()method was moved to newgetIdentityAndDurationFromCookie()andremoveIdentityCookie()methods. If you overrideloginByCookie()method, update it in order use new methods. -
Fixture console command syntax was changed from
yii fixture "*" -Usertoyii fixture "*, -User". Upgrade your scripts if necessary.
Upgrade from Yii 2.0.7
-
The signature of
yii\helpers\BaseArrayHelper::index()was changed. The method has got an extra optional parameter$groups. -
yii\helpers\BaseArrayHelpermethodsisIn()andisSubset()throw\yii\base\InvalidParamExceptioninstead of\InvalidArgumentException. If you wrap calls of these methods in try/catch block, change expected exception class. -
yii\rbac\ManagerInterface::canAddChild()method was added. If you have custom backend for RBAC you need to implement it. -
The signature of
yii\web\User::loginRequired()was changed. The method has got an extra optional parameter$checkAcceptHeader. -
The signature of
yii\db\ColumnSchemaBuilder::__construct()was changed. The method has got an extra optional parameter$db. In case you are instantiating this class yourself and using the$configparameter, you will need to move it to the right by one. -
String types in the MSSQL column schema map were upgraded to Unicode storage types. This will have no effect on existing columns, but any new columns you generate via the migrations engine will now store data as Unicode.
-
Output buffering was introduced in the pair of
yii\widgets\ActiveForm::init()and::run(). If you override any of these methods, make sure that output buffer handling is not corrupted. If you call the parent implementation, when overriding, everything should work fine. You should be doing that anyway.
Upgrade from Yii 2.0.6
-
Added new requirement: ICU Data version >= 49.1. Please, ensure that your environment has ICU data installed and up to date to prevent unexpected behavior or crashes. This may not be the case on older systems e.g. running Debian Wheezy.
Tip: Use Yii 2 Requirements checker for easy and fast check. Look for
requirements.phpin root of Basic and Advanced templates (howto-comment is in head of the script). -
The signature of
yii\helpers\BaseInflector::transliterate()was changed. The method is now public and has an extra optional parameter$transliterator. -
In
yii\web\UrlRulethepatternmatching group names are being replaced with the placeholders on class initialization to support wider range of allowed characters. Because of this change:- You are required to flush your application cache to remove outdated
UrlRuleserialized objects. See the Cache Flushing Guide - If you implement
parseRequest()orcreateUrl()and rely on parameter names, callsubstitutePlaceholderNames()in order to replace temporary IDs with parameter names after doing matching.
- You are required to flush your application cache to remove outdated
-
The context of
yii.confirmJavaScript function was changed fromyiiobject to the DOM element which triggered the event.- If you overrode the
yii.confirmfunction and accessed theyiiobject throughthis, you must access it with global variableyiiinstead.
- If you overrode the
-
Traversable objects are now formatted as arrays in XML response to support SPL objects and Generators. Previous behavior could be turned on by setting
XmlResponseFormatter::$useTraversableAsArraytofalse. -
If you've implemented
yii\rbac\ManagerInterfaceyou need to implement additional methodgetUserIdsByRole($roleName). -
If you're using ApcCache with APCu, set
useApcutotruein the component config. -
The
yii\behaviors\SluggableBehaviorclass has been refactored to make it more reusable. Added newprotectedmethods:isSlugNeeded()makeUnique()
The visibility of the following Methods has changed from
privatetoprotected:validateSlug()generateUniqueSlug()
-
The
yii\console\controllers\MessageControllerclass has been refactored to be better configurable and now also allows setting a lot of configuration options via command line. If you extend from this class, make sure it works as expected after these changes.
Upgrade from Yii 2.0.5
- The signature of the following methods in
yii\console\controllers\MessageControllerhas changed. They have an extra parameter$markUnused.saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
Upgrade from Yii 2.0.4
Upgrading from 2.0.4 to 2.0.5 does not require any changes.
Upgrade from Yii 2.0.3
-
Updated dependency to
cebe/markdownto version1.1.x. If you need stick with 1.0.x, you can specify that in yourcomposer.jsonby adding the following line in therequiresection:"cebe/markdown": "~1.0.0",
Upgrade from Yii 2.0.2
Starting from version 2.0.3 Yii Security component relies on OpenSSL crypto lib instead of Mcrypt. The reason is that
Mcrypt is abandoned and isn't maintained for years. Therefore your PHP should be compiled with OpenSSL support. Most
probably there's nothing to worry because it is quite typical.
If you've extended yii\base\Security to override any of the config constants you have to update your code:
- `MCRYPT_CIPHER` — now encoded in `$cipher` (and hence `$allowedCiphers`).
- `MCRYPT_MODE` — now encoded in `$cipher` (and hence `$allowedCiphers`).
- `KEY_SIZE` — now encoded in `$cipher` (and hence `$allowedCiphers`).
- `KDF_HASH` — now `$kdfHash`.
- `MAC_HASH` — now `$macHash`.
- `AUTH_KEY_INFO` — now `$authKeyInfo`.
Upgrade from Yii 2.0.0
-
Upgraded Twitter Bootstrap to version 3.3.x. If you need to use an older version (i.e. stick with 3.2.x) you can specify that in your
composer.jsonby adding the following line in therequiresection:"bower-asset/bootstrap": "3.2.*",
Upgrade from Yii 2.0 RC
-
If you've implemented
yii\rbac\ManagerInterfaceyou need to add implementation for new methodremoveChildren(). -
The input dates for datetime formatting are now assumed to be in UTC unless a timezone is explicitly given. Before, the timezone assumed for input dates was the default timezone set by PHP which is the same as
Yii::$app->timeZone. This causes trouble because the formatter usesYii::$app->timeZoneas the default values for output so no timezone conversion was possible. If your timestamps are stored in the database without a timezone identifier you have to ensure they are in UTC or add a timezone identifier explicitly. -
yii\bootstrap\Collapseis now encoding labels by default.encodeitem option and globalencodeLabelsproperty were introduced to disable it. Keys are no longer used as labels. You need to remove keys and uselabelitem option instead. -
The
yii\base\View::beforeRender()andyii\base\View::afterRender()methods have two extra parameters$viewFileand$params. If you are overriding these methods, you should adjust the method signature accordingly. -
If you've used
asImageformatter i.e.Yii::$app->formatter->asImage($value, $alt);you should change it toYii::$app->formatter->asImage($value, ['alt' => $alt]);. -
Yii now requires
cebe/markdown1.0.0 or higher, which includes breaking changes in its internal API. If you extend the markdown class you need to update your implementation. See https://github.com/cebe/markdown/releases/tag/1.0.0-rc for details. If you just used the markdown helper class there is no need to change anything. -
If you are using CUBRID DBMS, make sure to use at least version 9.3.0 as the server and also as the PDO extension. Quoting of values is broken in prior versions and Yii has no reliable way to work around this issue. A workaround that may have worked before has been removed in this release because it was not reliable.
Upgrade from Yii 2.0 Beta
-
If you are using Composer to upgrade Yii, you should run the following command first (once for all) to install the composer-asset-plugin, before you update your project:
php composer.phar global require "fxp/composer-asset-plugin:~1.3.1"You also need to add the following code to your project's
composer.jsonfile:"extra": { "asset-installer-paths": { "npm-asset-library": "vendor/npm", "bower-asset-library": "vendor/bower" } }It is also a good idea to upgrade composer itself to the latest version if you see any problems:
composer self-update -
If you used
clearAll()orclearAllAssignments()ofyii\rbac\DbManager, you should replace them withremoveAll()andremoveAllAssignments()respectively. -
If you created RBAC rule classes, you should modify their
execute()method by adding$useras the first parameter:execute($user, $item, $params). The$userparameter represents the ID of the user currently being access checked. Previously, this is passed via$params['user']. -
If you override
yii\grid\DataColumn::getDataCellValue()with visibilityprotectedyou have to change visibility topublicas visibility of the base method has changed. -
If you have classes implementing
yii\web\IdentityInterface(very common), you should modify the signature offindIdentityByAccessToken()aspublic static function findIdentityByAccessToken($token, $type = null). The new$typeparameter will contain the type information about the access token. For example, if you useyii\filters\auth\HttpBearerAuthauthentication method, the value of this parameter will beyii\filters\auth\HttpBearerAuth. This allows you to differentiate access tokens taken by different authentication methods. -
If you are sharing the same cache across different applications, you should configure the
keyPrefixproperty of the cache component to use some unique string. Previously, this property was automatically assigned with a unique string. -
If you are using
dropDownList(),listBox(),activeDropDownList(), oractiveListBox()ofyii\helpers\Html, and your list options use multiple blank spaces to format and align option label texts, you need to specify the optionencodeSpacesto be true. -
If you are using
yii\grid\GridViewand have configured a data column to use a PHP callable to return cell values (viayii\grid\DataColumn::value), you may need to adjust the signature of the callable to befunction ($model, $key, $index, $widget). The$keyparameter was newly added in this release. -
yii\console\controllers\AssetControlleris now using hashes instead of timestamps. Replace all{ts}with{hash}. -
The database table of the
yii\log\DbTargetnow needs aprefixcolumn to store context information. You can add it withALTER TABLE log ADD COLUMN prefix TEXT AFTER log_time;. -
The
fileinfoPHP extension is now required by Yii. If you useyii\helpers\FileHelper::getMimeType(), make sure you have enabled this extension. This extension is builtin in php above5.3. -
Please update your main layout file by adding this line in the
<head>section:<?= Html::csrfMetaTags() ?>. This change is needed becauseyii\web\Viewno longer automatically generates CSRF meta tags due to issue #3358. -
If your model code is using the
filevalidation rule, you should rename itstypesoption toextensions. -
MailEventclass has been moved to theyii\mailnamespace. You have to adjust all references that may exist in your code. -
The behavior and signature of
ActiveRecord::afterSave()has changed.ActiveRecord::$isNewRecordwill now always be false in afterSave and also dirty attributes are not available. This change has been made to have a more consistent and expected behavior. The changed attributes are now available in the new parameter of afterSave()$changedAttributes.$changedAttributescontains the old values of attributes that had changed and were saved. -
ActiveRecord::updateAttributes()has been changed to not trigger events and not respect optimistic locking anymore to differentiate it more from callingupdate(false)and to ensure it can be used inafterSave()without triggering infinite loops. -
If you are developing RESTful APIs and using an authentication method such as
yii\filters\auth\HttpBasicAuth, you should explicitly configureyii\web\User::enableSessionin the application configuration to be false to avoid starting a session when authentication is performed. Previously this was done automatically by authentication method. -
mailcomponent was renamed tomailer,yii\log\EmailTarget::$mailwas renamed toyii\log\EmailTarget::$mailer. Please update all references in the code and config files. -
yii\caching\GroupDependencywas renamed toTagDependency. You should create such a dependency using the codenew \yii\caching\TagDependency(['tags' => 'TagName']), whereTagNameis similar to the group name that you previously used. -
If you are using the constant
YII_PATHin your code, you should rename it toYII2_PATHnow. -
You must explicitly configure
yii\web\Request::cookieValidationKeywith a secret key. Previously this is done automatically. To do so, modify your application configuration like the following:return [ // ... 'components' => [ 'request' => [ 'cookieValidationKey' => 'your secret key here', ], ], ];Note: If you are using the
Advanced Project Templateyou should not add this configuration tocommon/configorconsole/configbecause the console application doesn't have to deal with CSRF and uses its own request that doesn't havecookieValidationKeyproperty. -
yii\rbac\PhpManagernow stores data in three separate files instead of one. In order to convert old file to new ones save the following code asconvert.phpthat should be placed in the same directory yourrbac.phpis in:<?php $oldFile = 'rbac.php'; $itemsFile = 'items.php'; $assignmentsFile = 'assignments.php'; $rulesFile = 'rules.php'; $oldData = include $oldFile; function saveToFile($data, $fileName) { $out = var_export($data, true); $out = "<?php\nreturn " . $out . ';'; $out = str_replace(['array (', ')'], ['[', ']'], $out); file_put_contents($fileName, $out, LOCK_EX); } $items = []; $assignments = []; if (isset($oldData['items'])) { foreach ($oldData['items'] as $name => $data) { if (isset($data['assignments'])) { foreach ($data['assignments'] as $userId => $assignmentData) { $assignments[$userId][] = $assignmentData['roleName']; } unset($data['assignments']); } $items[$name] = $data; } } $rules = []; if (isset($oldData['rules'])) { $rules = $oldData['rules']; } saveToFile($items, $itemsFile); saveToFile($assignments, $assignmentsFile); saveToFile($rules, $rulesFile); echo "Done!\n";Run it once, delete
rbac.php. If you've configuredauthFileproperty, remove the line from config and instead configureitemFile,assignmentFileandruleFile. -
Static helper
yii\helpers\Securityhas been converted into an application component. You should change all usage of its methods to a new syntax, for example: instead ofyii\helpers\Security::hashData()useYii::$app->getSecurity()->hashData(). ThegenerateRandomKey()method now produces not an ASCII compatible output. UsegenerateRandomString()instead. Default encryption and hash parameters has been upgraded. If you need to decrypt/validate data that was encrypted/hashed before, use the following configuration of the 'security' component:return [ 'components' => [ 'security' => [ 'derivationIterations' => 1000, ], // ... ], // ... ]; -
If you are using query caching, you should modify your relevant code as follows, as
beginCache()andendCache()are replaced bycache():$db->cache(function ($db) { // ... SQL queries that need to use query caching }, $duration, $dependency); -
Due to significant changes to security you need to upgrade your code to use
\yii\base\Securitycomponent instead of helper. If you have any data encrypted it should be re-encrypted. In order to do so you can use old security helper as explained by @docsolver at github. -
yii\helpers\Url::to() will no longer prefix base URL to relative URLs. For example,
Url::to('images/logo.png')will returnimages/logo.pngdirectly. If you want a relative URL to be prefix with base URL, you should make use of the alias@web. For example,Url::to('@web/images/logo.png')will return/BaseUrl/images/logo.png. -
The following properties are now taking
falseinstead ofnullfor "don't use" case:yii\bootstrap\NavBar::$brandLabel.yii\bootstrap\NavBar::$brandUrl.yii\bootstrap\Modal::$closeButton.yii\bootstrap\Modal::$toggleButton.yii\bootstrap\Alert::$closeButton.yii\widgets\LinkPager::$nextPageLabel.yii\widgets\LinkPager::$prevPageLabel.yii\widgets\LinkPager::$firstPageLabel.yii\widgets\LinkPager::$lastPageLabel.
-
The format of the Faker fixture template is changed. For an example, please refer to the file
apps/advanced/common/tests/templates/fixtures/user.php. -
The signature of all file downloading methods in
yii\web\Responseis changed, as summarized below:sendFile($filePath, $attachmentName = null, $options = [])sendContentAsFile($content, $attachmentName, $options = [])sendStreamAsFile($handle, $attachmentName, $options = [])xSendFile($filePath, $attachmentName = null, $options = [])
-
The signature of callbacks used in
yii\base\ArrayableTrait::fields()is changed fromfunction ($field, $model) {tofunction ($model, $field) {. -
Html::radio(),Html::checkbox(),Html::radioList(),Html::checkboxList()no longer generate the container tag around each radio/checkbox when you specify labels for them. You should manually render such container tags, or set theitemoption forHtml::radioList(),Html::checkboxList()to generate the container tags. -
The formatter class has been refactored to have only one class regardless whether PHP intl extension is installed or not. Functionality of
yii\base\Formatterhas been merged intoyii\i18n\Formatterandyii\base\Formatterhas been removed so you have to replace all usage ofyii\base\Formatterwithyii\i18n\Formatterin your code. Also the API of the Formatter class has changed in many ways. The signature of the following Methods has changed:asDateasTimeasDatetimeasSizehas been split up intoasSizeandasShortSizeasCurrencyasDecimalasPercentasScientific
The following methods have been removed, this also means that the corresponding format which may be used by a GridView or DetailView is not available anymore:
asNumberasDouble
Also due to these changes some formatting defaults have changes so you have to check all your GridView and DetailView configuration and make sure the formatting is displayed correctly.
The configuration for
asSize()has changed. It now uses the configuration for the number formatting from intl and only the base is configured using$sizeFormatBase.The specification of the date and time formats is now using the ICU pattern format even if PHP intl extension is not installed. You can prefix a date format with
php:to use the old format of the PHPdate()-function. -
The DateValidator has been refactored to use the same format as the Formatter class now (see previous change). When you use the DateValidator and did not specify a format it will now be what is configured in the formatter class instead of 'Y-m-d'. To get the old behavior of the DateValidator you have to set the format explicitly in your validation rule:
['attributeName', 'date', 'format' => 'php:Y-m-d'], -
beforeValidate(),beforeValidateAll(),afterValidate(),afterValidateAll(),ajaxBeforeSend()andajaxComplete()are removed fromActiveForm. The same functionality is now achieved via JavaScript event mechanism like the following:$('#myform').on('beforeValidate', function (event, messages, deferreds) { // called when the validation is triggered by submitting the form // return false if you want to cancel the validation for the whole form }).on('beforeValidateAttribute', function (event, attribute, messages, deferreds) { // before validating an attribute // return false if you want to cancel the validation for the attribute }).on('afterValidateAttribute', function (event, attribute, messages) { // ... }).on('afterValidate', function (event, messages) { // ... }).on('beforeSubmit', function () { // after all validations have passed // you can do ajax form submission here // return false if you want to stop form submission }); -
The signature of
View::registerJsFile()andView::registerCssFile()has changed. The$dependsand$positionparamaters have been merged into$options. The new signatures are as follows:registerJsFile($url, $options = [], $key = null)registerCssFile($url, $options = [], $key = null)