This file contains the upgrade notes for Yii 3.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 compatibility (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. While upgrade to Yii 3.0 might require substantial changes to both your application and extensions, the changes are bearable and require "refactoring", not "rewrite". All the "Yes, it is" cool stuff and Yii soul are still in place.
Changes summary:
- PHP requirements were raised to 7.1 and HHVM support dropped.
- Yii switches to semver since 3.0.
- Subtree-split is not used anymore.
- Dropped Yii own class autoloader in favor of the one provided with Composer.
- Framework GitHub repository and Packagist package are renamed and split into parts:
- yiisoft/yii-core - this package, the Yii Framework Core.
- Yii 2.0 development stays at yiisoft/yii2 repository. Bug and security fixes are expected. New features and enhancements are not accepted. Pull requests and maintainers are very welcome.
- yiisoft/di - PSR-11 compatible Dependency Injection container.
- yiisoft/log - PSR-3 compatible logging library.
- yiisoft/cache - PSR-16 compatible caching library.
- yiisoft/db - DataBase abstraction and QueryBuilder.
- yiisoft/db-mysql - MySQL Server DB extension.
- yiisoft/db-pgsql - PostgreSQL Server DB extension.
- yiisoft/db-sqlite - SQLite Server DB extension.
- yiisoft/db-mssql - MSSQL Server DB extension.
- yiisoft/db-oracle - Oracle DB extension.
- yiisoft/active-record - ActiveRecord library.
- yiisoft/rbac - Role-Based Access Control library.
- yiisoft/view - view rendering library: view and widgets.
- yiisoft/yii-web - Web extension.
- yiisoft/yii-rest - REST API extension.
- yiisoft/yii-console - console extension.
- yiisoft/yii-jquery - JQuery extension.
- yiisoft/yii-bootstrap3 - Bootstrap 3 extension.
- yiisoft/yii-bootstrap4 - Bootstrap 4 extension.
- yiisoft/yii-dataview - data displaying extension.
- yiisoft/yii-masked-input - Masked input field widget.
- yiisoft/yii-captcha - CAPTCHA extension.
- Please check package naming convention to get an idea about package names.
- Also please see full list of packages.
- More PSR compatibility: PSR-3, PSR-11, PSR-16
- Framework core requires only virtual PSR implementation packages, you are free to choose your logger and cache implementations. More PSR implementations compatibility is expected later.
- Removed
ServiceLocatorfromApplicationandModule, DI container is used instead. - Database abstraction is split in several packages allowing independent use.
- Removed PJAX support.
- Cubrid DB is not supported anymore.
- Profiling and logging got separated.
- yiisoft/yii2-composer plugin is not used anymore.
- All the configuration made explicit in
configfolders of all the packages and recommended to be used with composer-config-plugin. - yii\base\Configurable interface and logic are removed in favour of DI and yii\di\Initiable interface.
So
BaseObjectclass and it's descendants don't have$configparameter in their constructors anymore. But it can be added where appropriate. E.g. seeyii\validators\Validator::__construct(). - No advanced app anymore. Application templating approach has been changed, please see:
- yiisoft/yii-project-template - project template;
- yiisoft/yii-base-web - web application base.
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 back up anyway ;)
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.
-
PHP requirements were raised to 7.1. Make sure your code is updated accordingly.
-
memcachePECL extension support was dropped. UsememcachedPECL extension instead. -
Removed
Configurableandinit()fromBaseObject__construct(array $config = [])is not supported- use yii\di\Initiable interface if you want
init()function to be called by DI after construction of your class object
-
Yiihelper is redone and doesn't provide "global vars" anymore:- change
use Yiitouse yii\helpers\Yii Yii::$appis not available:- prefer to use constructor DI to get application and services
- use
Yii::get('service')instead ofYii::$app->getService() - use
Yii::getApp()if everything else fails
- aliases were moved to
Aliasesservice:- prefered wat to resolve aliases:
- DI injected
aliasesservice or $this->app->getAlias()
- DI injected
- prefered way to set aliases is through configuration
- prefered wat to resolve aliases:
- added and used
Application::t()- prefer
$this->app->t()overYii::t()
- prefer
- removed
Yii::configure()- use
yii\di\AbstractContainer::configure()if everything else fails
- use
Yii::$containermade private:- don't use it explicitly
- use container implicitly with constructor DI
- no need to require Yii class from entry script
- to use
Yiifeatures useYii::setContainer()- for it could access logger, profiler and i18n
- else Yii functions will have generic behavior
- see recommended entry script
- removed
Yii::$loggerandYii::$profiler, use DI instead - constant definitions moved to
config/defines.phpYII_DEBUGdefaults toYII_ENV_DEVYII2_PATHrenamed toYII_PATH
getObjectVars()moved toArrayHelper
- change
-
Removed
ServiceLocatorfromApplicationandModule:- no own components in app and modules
- get services implicitly with DI
-
Refactored internationalization:
- Added Locale class able to parse BCP 47 locale strings. It's used instead of language.
Application::setEncodingmethod- encoding saved to
ini_set('default_charset')andmb_internal_encoding()and thus applied by default to all PHP string functions likemb_*
- encoding saved to
-
Moved files around for more logic organization and more readable directories:
- globally:
- all exceptions moved into separate dirs in all packages
- yii-web:
- moved web formatters to their own directory
- cache:
- renamed namespace
yii\caching->Yiisoft\Cache - moved cache dependencies to own directory
- renamed namespace
- yii-project-template:
- moved web server root dir to
public(was web)
- moved web server root dir to
- globally:
-
Moved data displaying widgets to own package yiisoft/yii-dataview:
yii\grid->Yiisoft\Yii\DataViewyii\grid\*Column->Yiisoft\Yii\DataView\Columns\*yii\widgets\ListView->Yiisoft\Yii\DataView\ListViewyii\widgets\DetailView->Yiisoft\Yii\DataView\DetailView
-
DI:
- Config changed to be DI container config instead of application.
- Removed
yii\di\Instanceclass:- Use
yii\di\Referenceinstead - Use
yii\di\Factory::ensure()orYii::ensureObject()instead ofInstance::ensure()
- Use
-
Events were refactored:
- event name constants moved to event classes:
yii\base\Application::EVENT_BEFORE_ACTION->yii\base\ActionEvent::BEFOREyii\base\Application::EVENT_AFTER_ACTION->yii\base\ActionEvent::AFTERyii\base\Application::EVENT_BEFORE_REQUEST->yii\base\RequestEvent::BEFOREyii\base\Application::EVENT_AFTER_REQUEST->yii\base\RequestEvent::AFTERyii\base\View::EVENT_END_BODY->yii\view\BodyEvent::ENDyii\base\View::EVENT_BEGIN_BODY->yii\view\BodyEvent::BEGINyii\base\Response::EVENT_BEFORE_PREPARE->yii\base\PrepareEvent::BEFORE(to be done)yii\base\Response::EVENT_AFTER_PREPARE->yii\base\PrepareEvent::AFTER(to be done)
- event name constants moved to event classes:
-
Added default application configuration and support for config assembling with composer-config-plugin.
-
Tests:
- Renamed
yiiunitnamespace toyii\tests - Added
testsconfig
- Renamed
-
Following new methods have been added to
yii\mail\MessageInterfaceaddHeader(),setHeader(),getHeader(),setHeaders()providing ability to setup custom mail headers. Make sure your provide implementation for those methods, while creating your own mailer solution. -
::className()method calls should be replaced with native::class. When upgrading to Yii 3.0, You should do a global search and replace for::className()to::class. All calls on objects via->className()should be replaced by a call toget_class(). -
Dependency injection (DI) layer has been replaced by "yiisoft/di" package. Make sure to update class/object definitions at your code to match the syntax used by it. In particular: you should use '__class' array key instead of 'class' for class name specification.
-
XCache and Zend data cache support was removed. Switch to another caching backends.
-
Rename
InvalidParamExceptionusage toInvalidArgumentException. -
CAPTCHA package has been moved into separate extension https://github.com/yiisoft/yii-captcha. Include it in your composer.json if you use it.
-
JQuery related code (e.g.
yii.js,yiiActiveForm.js,yiiGridView.js) has been moved into separate extension https://github.com/yiisoft/yii-jquery. Include it in your composer.json if you use it. -
REST API package has been moved into separate extension https://github.com/yiisoft/yii-rest. Include it in your composer.json if you use it.
-
MSSQL Server DB package has been moved into separate extension https://github.com/yiisoft/yii-mssql. Include it in your composer.json if you use it.
-
Oracle DB package has been moved into separate extension https://github.com/yiisoft/yii-oracle. Include it in your composer.json if you use it.
-
CUBRID support has been removed, package
Yiisoft\Db\cubrid\*is no longer available. If you need to use CUBRID further you should create your own integration for it. -
Masked input field widget was moved into separate extension https://github.com/yiisoft/yii-masked-input. Include it in your composer.json if you use it.
-
PJAX support has been removed: widget
yii\widget\Pjax, methodyii\web\Request::getIsPjax(), PJAX related checks and headers are no longer available. If you wish to use PJAX further you should create your own integration for it. -
If you've used ApcCache and set
useApcuin your config, remove the option. -
During mail view rendering the
$messagevariable is no longer set by default to be an instance ofyii\mail\MessageInterface. Instead it is available via$this->context->messageexpression. -
yii\mail\BaseMailer::render()method has been removed. Make sure you do not use it anywhere in your program. Mail view rendering is now encapsulated intoyii\mail\Templateclass. -
Properties
view,viewPath,htmlLayoutandtextLayouthave been moved fromyii\mail\BaseMailertoyii\mail\Composerclass, which now encapsulates message composition. -
Interface of
Yiisoft\Log\Loggerhas been changed according to PSR-3Psr\Log\LoggerInterface. Make sure you update your code accordingly in case you invokeLoggermethods directly. -
Constants
Yiisoft\Log\Logger::LEVEL_ERROR,Yiisoft\Log\Logger::LEVEL_WARNINGand so on have been removed. Use constants fromPsr\Log\LogLevelinstead. -
Method
yii\BaseYii::trace()has been renamed todebug(). Make sure you use correct name for it. -
Class
Yiisoft\Log\Dispatcherhas been removed as well as application 'log' component. Log targets now should be configured usingyii\base\Application::$loggerproperty. Neither 'log' or 'logger' components should be present atyii\base\Application::$bootstrap -
Profiling related functionality has been extracted into a separated component under
yii\profile\ProfilerInterface. Profiling messages should be collection usingyii\base\Application::$profiler. In case you wish to continue storing profiling messages along with the log ones, you may useyii\profile\LogTargetprofiling target. -
Classes
yii\web\Requestandyii\web\Responsehave been updated to match interfacesPsr\Http\Message\ServerRequestInterfaceandPsr\Http\Message\ResponseInterfaceaccordingly. Make sure you use their methods and properties correctly. In particular: methodgetHeaders()and corresponding virtual property$headersare no longer returnHeaderCollectioninstance, you can usegetHeaderCollection()in order to use old headers setup syntax;Request|Response::$versionrenamed toRequest|Response::$protocolVersion;Response::$statusTextrenamedResponse::$reasonPhrase;Request::$bodyParamsrenamed toRequest::$parsedBody;Request::getBodyParam()renamed toRequest::getParsedBodyParam(); -
yii\web\Response::$streamis no longer available, useyii\web\Response::withBody()to setup stream response. You can useResponse::$bodyRangeto setup stream content range. -
Classes
yii\web\CookieCollection,yii\web\HeaderCollectionandyii\web\UploadedFilehave been moved under namespaceyii\http\*. Make sure to refer to those classes using correct fully qualified name. -
Public interface of
UploadedFileclass has been changed according toPsr\Http\Message\UploadedFileInterface. Make sure you refer to its properties and methods with correct names. -
Yiisoft\Yii\Captcha\CaptchaActionhas been refactored. Rendering logic was extracted intoYiisoft\Yii\Captcha\DriverInterface, which instance is available viaYiisoft\Yii\Captcha\CaptchaAction::$driverfield. All image settings now should be passed to the driver fields instead of action. Automatic detection of the rendering driver is no longer supported. -
Yiisoft\Yii\Captcha\Captcha::checkRequirements()method has been removed. -
All cache related classes interface has been changed according to PSR-16 "Simple Cache" specification. Make sure you change your invocations for the cache methods accordingly. The most notable changes affects methods
get()andgetMultiple()as they now accept$defaultargument, which value will be returned in case there is no value in the cache. This makes the default return value to benullinstead offalse. -
Particular cache implementation should now be configured as
yii\caching\Cache::$handlerproperty instead of the component itself. Properties$defaultTtl,$serializerand$keyPrefixhas been moved to cache handler and should be configured there. Creating your own cache implementation you should implement\Psr\SimpleCache\CacheInterfaceor extendyii\caching\SimpleCacheabstract class. Useyii\caching\CacheInterfaceonly if you wish to replaceyii\caching\Cachecomponent providing your own solution for cache dependency handling. -
yii\caching\SimpleCache::$serializernow should beyii\serialize\SerializerInterfaceinstance or its DI compatible configuration. Thus it does no longer accept pair of serialize/unserialize functions as an array. Useyii\serialize\CallbackSerializeror other predefined serializer class fromyii\serialize\*namespace instead. -
Console command used to clear cache now calls related actions "clear" instead of "flush".
-
Yii autoloader was removed in favor of Composer-generated one. You should remove explicit inclusion of
Yii.phpfrom your entryindex.phpscripts. In case you have relied on class map, usecomposer.jsoninstead of configuring it with PHP. For details please refer to guide on autoloading, guide on customizing helpers and guide on Working with Third-Party Code. -
The signature of
yii\web\RequestParserInterface::parse()was changed. The method now accepts theyii\web\Requestinstance as a sole argument. Make sure you declare and implement this method correctly, while creating your own request parser. -
Uploaded file retrieve methods have been moved from
yii\http\UploadedFiletoyii\web\Request. You should useRequest::getUploadedFileByName()instead ofUploadedFile::getInstanceByName()andRequest::getUploadedFilesByName()instead ofUploadedFile::getInstancesByName(). Instead ofUploadedFile::getInstance()andUploadedFile::getInstances()use construction$model->load(Yii::$app->request->getUploadedFiles()). -
Result of
yii\web\Request::getBodyParams()now includes uploaded files (e.g. result ofyii\web\Request::getUploadedFiles()). You should aware that instances ofyii\http\UploadedFilemay appear inside body params. -
The following method signature have changed. If you override any of them in your code, you have to adjust these places:
Yiisoft\Db\QueryBuilder::buildGroupBy($columns)->buildGroupBy($columns, &$params)Yiisoft\Db\QueryBuilder::buildOrderByAndLimit($sql, $orderBy, $limit, $offset)->buildOrderByAndLimit($sql, $orderBy, $limit, $offset, &$params)yii\widgets\ActiveField::hint($content = null, $options = [])yii\base\View::renderDynamic($statements)->yii\base\View::renderDynamic($statements, array $params = []) -
yii\filters\AccessControlhas been optimized by only instantiating rules at the moment of use. This could lead to a potential BC-break if you are depending on $rules to be instantiated in init(). -
yii\widgets\BaseListView::run()andyii\widgets\GridView::run()now return content, instead of echoing it. Normally we callBaseListView::widget()and for this case behavior is NOT changed. In case you call::run()method, ensure that its return is processed correctly. -
yii\web\UrlNormalizeris now enabled by default inyii\web\UrlManager. If you are usingyii\web\Request::resolve()oryii\web\UrlManager::parseRequest()directly, make sure that all potential exceptions are handled correctly or setyii\web\UrlNormalizer::$normalizertofalseto disable normalizer. -
yii\base\InvalidParamExceptionwas renamed toyii\base\InvalidArgumentException. -
Classes
yii\widgets\ActiveForm,yii\widgets\ActiveField,yii\grid\GridView,yii\web\Viewhave been refactored to be more generic without including any 'JQuery' support and client-side processing (validation, automatic submit etc.). You should use widget behaviors fromYiisoft\Yii\JQuery\*package to make old code function as before. E.g. attachYiisoft\Yii\JQuery\ActiveFormClientScripttoyii\widgets\ActiveForm,Yiisoft\Yii\JQuery\GridViewClientScripttoyii\grid\GridViewand so on. -
Fields
$enableClientScriptand$attributeshave been removed fromyii\widgets\ActiveForm. Make sure you do not use them or specify them duringActiveForm::begin()invocation. -
Field
yii\grid\GridView::$filterSelectorhas been removed. Make sure you do not use it or specify it duringGridView::widget()invocation. UseYiisoft\Yii\JQuery\GridViewClientScript::$filterSelectorinstead. -
Method
getClientOptions()has been removed fromyii\validators\Validatorand all its descendants. All implementations ofclientValidateAttribute()around built-in validators now returnnull. Use classes fromYiisoft\Yii\JQuery\Validators\Client\*for building client validation (JavaScript) code. -
Assets
yii\web\JqueryAsset,yii\web\YiiAsset,yii\validators\ValidationAssethave been moved underYiisoft\Yii\JQuery\*namespace. Make sure you refer to the new full-qualified names of this classes. -
Methods
yii\validators\Validator::formatMessage(),yii\validators\IpValidator::getIpParsePattern()andyii\validators\FileValidator::buildMimeTypeRegexp()have been madepublic. Make sure you use correct access level specification in case you override these methods. -
Default script position for the
yii\web\View::registerJs()changed toView::POS_END. -
Package "ezyang/htmlpurifier" has been made optional and is not installed by default. If you need to use
yii\helpers\HtmlPurifieroryii\i18n\Formatter::asHtml()(e.g. 'html' data format), you'll have to install this package manually for your project. -
yii\BaseYii::powered()method has been removed. Please add "Powered by Yii" link either right into HTML or usingyii\helpers\Html::a(). -
Public interface of the
yii\base\Eventclass have been changed to match commonly used event notations. Field$senderconverted into virtual property$target, field$dataconverted into virtual property$params. Public field$handledhas been removed - use methodsstopPropagation()andisPropagationStopped()instead. -
Signature of the methods
yii\base\Component::trigger()andyii\base\Event::trigger()has been changed, removing$nameargument and allowing$eventto be a string event name. Make sure you invoke these methods correctly and apply new signature in case you override them. -
yii\i18n\MessageFormatterno longer supports parameter names with.,-,=and other symbols that are used in pattern syntax following directly how it works in intl/ICU. If you use such parameters names, replace special symbols with_. -
yii\i18n\MessageFormatter::parse()method was removed. If you have a rare case where it's used copy-paste it from 2.0 branch to your project. -
yii\helpers\Markdownwas removed. Usecebe/markdowncomposer package directly. -
yii\helpers\FileHelpernow always uses/as normalized directory separator regardless of operating system used. Adjust your code that work with paths if needed. -
Ability to truncate content taking HTML into account was removed from
StringHelperin favor ofHtmlPurifierhelper.