本章将列出自1.1版本以来Yii 2.0的主要变化。


The most obvious change in Yii 2.0 is the use of namespaces. Almost every core class is namespaced, e.g., yii\web\Request. The “C” prefix is no longer used in class names. The naming of the namespaces follows the directory structure. For example, yii\web\Request indicates the corresponding class file is web/Request.php under the Yii framework folder. You can use any core class without explicitly including that class file, thanks to the Yii class loader.

Yii 2.0最明显的改变是对命名空间的使用。几乎所有的核心类都使用了命名空间,比如yii\web\Request。同时,类名前不再使用“C”前缀。命名空间的命名遵循目录结构,如yii\web\Request代表的相应类文件是位于Yii 框架的目录下的 web/Request.php。由于Yii的类装载机制,可以在未显示包含类文件的情况下使用任意的核心类。


Yii 2.0 breaks the CComponent class in 1.1 into two classes: [[yii\base\Object]] and [[yii\base\Component]]. The [[yii\base\Object|Object]] class is a lightweight base class that allows defining class properties via getters and setters. The [[yii\base\Component|Component]] class extends from [[yii\base\Object|Object]] and supports the event feature and the behavior feature.

Yii 2.0将1.1版本中的CComponent类拆分成两个类:[[yii\base\Object]] 和 [[yii\base\Component]]。其中,[[yii\base\Object|Object]]类是一个轻量级的基类,它通过getter 和setter提供了定义类属性(property)的方法。[[yii\base\Component|Component]]继承自[[yii \base\Object|Object]],并提供对事件(event)和行为(behavior)的支持。

If your class does not need the event or behavior feature, you should consider using Object as the base class. This is usually the case for classes that represent basic data structures.

如果自定义类不需要事件或行为特性,可考虑使用Object 作为基类。这通常用于表示基础的数据结构。

对象配置Object Configuration

The [[yii\base\Object|Object]] class introduces a uniform way of configuring objects. Any descendant class of [[yii\base\Object|Object]] should declare its constructor (if needed) in the following way so that it can be properly configured:


In the above, the last parameter of the constructor must take a configuration array which contains name-value pairs for initializing the properties at the end of the constructor. You can override the [[yii\base\Object::init()|init()]] method to do initialization work that should be done after the configuration is applied.


By following this convention, you will be able to create and configure a new object using a configuration array like the following:



There is no longer the need to define an on-method in order to define an event in Yii 2.0. Instead, you can use whatever event names. To attach a handler to an event, you should use the on method now:

在Yii 2.0中,不再需要定义一个以on为前缀的方法作为事件,而是可以作用任意的事件名称。要将一个事件处理函数handler绑定到一个事件,可以使用如下的on方法:

When you attach a handler, you can now associate it with some parameters which can be later accessed via the event parameter by the handler:


Because of this change, you can now use “global” events. Simply trigger and attach handlers to an event of the application instance:


If you need to handle all instances of a class instead of the object you can attach a handler like the following:


The code above defines a handler that will be triggered for every Active Record object’s EVENT_AFTER_INSERT event.

上面的代码定义了一个handler,他会在每个Active Record对象的EVENT_AFTER_INSERT事件发生时被触发。

路径别名(Path Alias)

Yii 2.0 expands the usage of path aliases to both file/directory paths and URLs. An alias must start with a @ character so that it can be differentiated from file/directory paths and URLs. For example, the alias @yii refers to the Yii installation directory. Path aliases are supported in most places in the Yii core code. For example, FileCache::cachePath can take both a path alias and a normal directory path.

Yii 2.0扩大了对路径别名的使用,[email protected],以便与文件目录路径和URL区别开来。比如,@yii代表Yii的安装路径。在Yii的核心代码中,路径别名都是支持的。比如FileCache::cachePath既可以作用于路径别名也可以作用于正常的文件路径。

Path alias is also closely related with class namespaces. It is recommended that a path alias be defined for each root namespace so that you can use Yii the class autoloader without any further configuration. For example, because @yii refers to the Yii installation directory, a class like yii\web\Request can be autoloaded by Yii. If you use a third party library such as Zend Framework, you may define a path alias @Zend which refers to its installation directory and Yii will be able to autoload any class in this library.

路径别名还与类的命名空间紧密关联。建议为每个根命名空间定义一个别名,如此可以利用Yii的类装载机制加载类而不需要额外的配置。比如,[email protected],一个诸如yii\web\Request的类就可以被Yii自动装载。如果使用了Zend Framework等第三方库,[email protected],那么Yii可以自动加载该库中的所有类。


Yii 2.0 introduces a [[yii\web\View|View]] class to represent the view part of the MVC pattern. It can be configured globally through the “view” application component. It is also accessible in any view file via $this. This is one of the biggest changes compared to 1.1: $this in a view file no longer refers to the controller or widget object. It refers to the view object that is used to render the view file. To access the controller or the widget object, you have to use $this->context now.

Yii 2.0引入了一个[[yii\web\View|View]]视图类以代表MVC模式中的V部分。可以在全局层面上通过application的“view”组件进行配置。也可以在视图文件中通过$this访问。与1.1版本相比,这是最大的变经之一:视图文件中的$this不再是一个控制器(controller)或一个挂件(widget)。

Because you can access the view object through the “view” application component, you can now render a view file like the following anywhere in your code, not necessarily in controllers or widgets:


Also, there is no more CClientScript in Yii 2.0. The [[yii\web\View|View]] class has taken over its role with significant improvements. For more details, please see the “assets” subsection.

同时,Yii 2.0中不再有CClientScript,[[yii\web\View|View]]类取代了它的角色,这是一个显著的改进。

While Yii 2.0 continues to use PHP as its main template language, it comes with two official extensions adding support for two popular template engines: Smarty and Twig. The Prado template engine is no longer supported. To use these template engines, you just need to use tpl as the file extension for your Smarty views, or twig for Twig views. You may also configure the [[yii\web\View::$renderers|View::$renderers]] property to use other template engines. See Using template engines section of the guide for more details.

Yii 2.0继续使用PHP作为其主要的模板(template)语言,同时还有两个官方的扩展(extension)以支持当前主流的两个模板引擎:Smarty和Twig。而Prado模板引擎不再支持。使用这些模板引擎,只需使用tpl或twig作为文件名的后缀,即可支持Smarty视图或Twig视图。还可以通过设置[[yii\web\View::$renderers|View::$renderers]]属性以使用其他模板引擎。


A model is now associated with a form name returned by its [[yii\base\Model::formName()|formName()]] method. This is mainly used when using HTML forms to collect user inputs for a model. Previously in 1.1, this is usually hardcoded as the class name of the model.


New methods called [[yii\base\Model::load()|load()] and [[yii\base\Model::loadMultiple()|Model::loadMultiple()]] are introduced to simplify the data population from user inputs to a model. For example,

引入了[[yii\base\Model::load()|load()] 和 [[yii\base\Model::loadMultiple()|Model::loadMultiple()]]两个新的方法用于简化将用户输入的数据填充到一个模型中。比如:

Yii 2.0 introduces a new method called [[yii\base\Model::scenarios()|scenarios()]] to declare which attributes require validation under which scenario. Child classes should overwrite [[yii\base\Model::scenarios()|scenarios()]] to return a list of scenarios and the corresponding attributes that need to be validated when [[yii\base\Model::validate()|validate()]] is called. For example,

Yii 2.0引入了[[yii\base\Model::scenarios()|scenarios()]]新方法,用以声明哪些属性 (attributes)在哪些场景下需要验证。子类需重载[[yii\base\Model::scenarios()|scenarios()]]方 法,并返一个包含场景及相应需要验证的属性的列表,以供调用[[yii\base\Model::validate()|validate()]]时使 用。如:

This method also determines which attributes are safe and which are not. In particular, given a scenario, if an attribute appears in the corresponding attribute list in [[yii\base\Model::scenarios()|scenarios()]] and the name is not prefixed with !, it is considered safe.

同时,这个方法也明确了哪些属性是安全的,哪些是不安全的。在实际操作中,给定一个场景,如果一个属性出现在[[yii\base\Model::scenarios()|scenarios()]]返回的列表中,且其名称没有加!的前缀,则其可视为 safe

Because of the above change, Yii 2.0 no longer has “unsafe” validator.

因此,Yii 2.0中不再有“unsafe”验证器(validator)。

If your model only has one scenario (very common), you do not have to overwrite [[yii\base\Model::scenarios()|scenarios()]], and everything will still work like the 1.1 way.



The [[yii\base\Controller::render()|render()]] and [[yii\base\Controller::renderPartial()|renderPartial()]] methods now return the rendering results instead of directly sending them out. You have to echo them explicitly, e.g., echo


[[yii\base\Controller::render()|render()]]和[[yii\base \Controller::renderPartial()|renderPartial()]]方法现在返回渲染后的结果,而不再是直接发送出去给用 户。因此,需要显式的用echo将结果发送出去。如:echo $this->render(…);。


Using a widget is more straightforward in 2.0. You mainly use the [[yii\base\Widget::begin()|begin()]], [[yii\base\Widget::end()|end()]] and [[yii\base\Widget::widget()|widget()]] methods of the [[yii\base\Widget|Widget]] class. For example,

在2.0版本中,使用挂件将更为直接。主要使用[[yii\base\Widget|Widget]]类的[[yii\base \Widget::begin()|begin()]],[[yii\base\Widget::end()|end()]] 和 [[yii\base\Widget::widget()|widget()]]方法。如:

Previously in 1.1, you would have to enter the widget class names as strings via the beginWidget(), endWidget() and widget() methods of CBaseController. The approach above gets better IDE support.



Themes work completely different in 2.0. They are now based on a path map to “translate” a source view into a themed view. For example, if the path map for a theme is [‘/web/views’ => ‘/web/themes/basic’], then the themed version for a view file /web/views/site/index.php will be /web/themes/basic/site/index.php.

在2.0版本中,主题以完全不同的方式运转。现在以一种将路径名映射、翻译为某主题的视图源文件的方式运转。比如,对主题的路径映射为[‘/web/views’ => ‘/web/themes/basic’],那么,其主题化后的视图文件/web/views/site/index.php将变成/web/themes/basic/site/index.php。

For this reason, theme can now be applied to any view file, even if a view rendered outside of the context of a controller or a widget.


There is no more CThemeManager. Instead, theme is a configurable property of the “view” application component.


命令行应用(Console Applications)

Console applications are now composed by controllers, like Web applications. In fact, console controllers and Web controllers share the same base controller class.


Each console controller is like CConsoleCommand in 1.1. It consists of one or several actions. You use the yii <route> command to execute a console command, where <route> stands for a controller route (e.g. sitemap/index). Additional anonymous arguments are passed as the parameters to the corresponding controller action method, and named arguments are treated as global options declared in globalOptions().

每个命令行控制器就像1.1版本中的CConsoleCommand,包含一个或多个action。可以使用yii <route>命令执行一个命令行命令, <route>代表一个控件器路由(如sitemap/index)。额外的匿名参数会被传递给相应的控制器中的action方法。而命名参数被视为像globalOptions()中的全局参数一样。

Yii 2.0 supports automatic generation of command help information from comment blocks.

Yii 2.0支持自动从注释块中生成一个命令的帮助信息。


Yii 2.0 removes date formatter and number formatter in favor of the PECL intl PHP module.

Yii 2.0中删除了数据和数字格式化器,而合用了PHP的PECL和intl模块。

Message translation is still supported, but managed via the “i18n” application component. The component manages a set of message sources, which allows you to use different message sources based on message categories. For more information, see the class documentation for I18N.


过滤器(Action Filters)

Action filters are implemented via behaviors now. You should extend from [[yii\base\ActionFilter]] to define a new filter. To use a filter, you should attach the filter class to the controller as a behavior. For example, to use the [[yii\web\AccessControl]] filter, you should have the following code in a controller:

Action过滤器已经改由行为(behavior)来实现。可以通过继承 [[yii\base\ActionFilter]] 来定义新的过滤器。使用一个过滤器,可以将一个过滤器类作为行为绑定到一个控制器。如,要使用[[yii\web\AccessControl]]过滤器 可以在控制器中进行如下编码:

For more on action filters see the Controller section.


Yii 2.0 introduces a new concept called asset bundle. It is similar to script packages (managed by CClientScript) in 1.1, but with better support.

Yii 2.0引入了一个asset bundle的新概念。就像1.1版本中的脚本包(由CClientScript管理)一样,但是更高级。

An asset bundle is a collection of asset files (e.g. JavaScript files, CSS files, image files, etc.) under a directory. Each asset bundle is represented as a class extending [[yii\web\AssetBundle]]. By registering an asset bundle via [[yii\web\AssetBundle::register()]], you will be able to make the assets in that bundle accessible via Web, and the current page will automatically contain the references to the JavaScript and CSS files specified in that bundle.

一个资源包是一些资源文件在一个目录下的集合,始JavaScript文件、CSS文件、图片等。每个资源包由一个继承自[[yii\web \AssetBundle]]的类来表征。使用[[yii\web\AssetBundle::register()]]来注册一个资源包,可以使资源包 中的资源可以通过Web访问,且当前的页面会自动地将包中的JavaScript和CSS文件引入进来。

To learn more about assets see the asset manager documentation.

静态工具类(Static Helpers)

Yii 2.0 introduces many commonly used static helper classes, such as [[yii\helpers\Html|Html]], [[yii\helpers\ArrayHelper|ArrayHelper]], [[yii\helpers\StringHelper|StringHelper]]. [[yii\helpers\FileHelper|FileHelper]], [[yii\helpers\Json|Json]], [[yii\helpers\Security|Security]], These classes are designed to be easily extended. Note that static classes are usually hard to extend because of the fixed class name references. But Yii 2.0 introduces the class map (via [[Yii::$classMap]]) to overcome this difficulty.

Yii 2.0引入了诸多常用的静态工具类,如[[yii\helpers\Html|Html]],[[yii\helpers \ArrayHelper|ArrayHelper]],[[yii\helpers\StringHelper|StringHelper]], [[yii\helpers\FileHelper|FileHelper]], [[yii\helpers\Json|Json]], [[yii\helpers\Security|Security]]这些类都设计成易于继承,尽管静态类由于固定的类名引用而通常不易继承。但是Yii 2.0引入了类映射(利用[[Yii::$classMap]])来克服这个困难。


Yii 2.0 introduces the field concept for building a form using [[yii\widgets\ActiveForm]]. A field is a container consisting of a label, an input, an error message, and/or a hint text. It is represented as an [[yii\widgets\ActiveField|ActiveField]] object. Using fields, you can build a form more cleanly than before:

Yii 2.0引入了field的概念用于通过[[yii\widgets\ActiveForm]]创建的表单。一个字段就是 一个包含了一个标签、一个input控件和一个错误信息/提示文本的容器,以[[yii\widgets \ActiveField|ActiveField]]类对象表示。使用字段,可以更简洁的创建表单:

查询构建器(Query Builder)

In 1.1, query building is scattered among several classes, including CDbCommand, CDbCriteria, and CDbCommandBuilder. Yii 2.0 uses [[yii\db\Query|Query]] to represent a DB query and [[yii\db\QueryBuilder|QueryBuilder]] to generate SQL statements from query objects. For example:

在1.1版本中,数据库查询的构建被分散到几个类中,如CDbCommand,CDbCriteria和CDbCommandBuilder。Yii 2.0使用 [[yii\db\Query|Query]]表示数据库查询,并使用[[yii\db\QueryBuilder|QueryBuilder]]从query对象生成SQL语句。如,

Best of all, such query building methods can be used together with [[yii\db\ActiveRecord|ActiveRecord]], as explained in the next sub-section.



[[yii\db\ActiveRecord|ActiveRecord]] has undergone significant changes in Yii 2.0. The most important one is the relational ActiveRecord query. In 1.1, you have to declare the relations in the relations() method. In 2.0, this is done via getter methods that return an [[yii\db\ActiveQuery|ActiveQuery]] object. For example, the following method declares an “orders” relation:

[[yii\db\ActiveRecord|ActiveRecord]]在Yii 2.0中经历了显著的变更。最为重要的方面是关联ActiveRecord查询。在1.1版本中,需要在relations() 方法中声明关系。而在2.0中,改为由一个返回[[yii\db\ActiveQuery|ActiveQuery]] 对象的getter方法来完成。比如,以下的方法声明了一个关于订单的关系:

You can use $customer->orders to access the customer’s orders. You can also use $customer->getOrders()->andWhere(‘status=1’)->all() to perform on-the-fly relational query with customized query conditions.


When loading relational records in an eager way, Yii 2.0 does it differently from 1.1. In particular, in 1.1 a JOIN query would be used to bring both the primary and the relational records; while in 2.0, two SQL statements are executed without using JOIN: the first statement brings back the primary records and the second brings back the relational records by filtering with the primary keys of the primary records.

在预先载入关系记录的方式上,Yii 2.0与1.1版本完全不同。在实际操作中,1.1版本使用一个JOIN查询以返回主记录和关联记录,而在2.0版本中,使用了两个SQL语句而非一个JOIN查询:第一个语句返回主记录,第二个语句返回与主记录主键关联的关联记录。

Yii 2.0 no longer uses the model() method when performing queries. Instead, you use the [[yii\db\ActiveRecord::find()|find()]] method:

Yii 2.0不再使用model()方法来执行查询,而改用[[yii\db\ActiveRecord::find()|find()]]方法:

The [[yii\db\ActiveRecord::find()|find()]] method returns an instance of [[yii\db\ActiveQuery|ActiveQuery]] which is a subclass of [[yii\db\Query]]. Therefore, you can use all query methods of [[yii\db\Query]].

[[yii\db\ActiveRecord::find()|find()]]方法返回一个[[yii\db \ActiveQuery|ActiveQuery]]实例,注意该[[yii\db\ActiveQuery|ActiveQuery]]是[[yii \db\Query]]的子类。因此,可以对其使用[[yii\db\Query]]的所有查询方法。

Instead of returning ActiveRecord objects, you may call [[yii\db\ActiveQuery::asArray()|ActiveQuery::asArray()]] to return results in terms of arrays. This is more efficient and is especially useful when you need to return a large number of records:


By default, ActiveRecord now only saves dirty attributes. In 1.1, all attributes are saved to database when you ActiveRecordcall save(), regardless of having changed or not, unless you explicitly list the attributes to save.


Scopes are now defined in a custom [[yii\db\ActiveQuery|ActiveQuery]] class instead of model directly.


See active record docs for more details.

自动引用表名和列名 Auto-quoting Table and Column Names

Yii 2.0 supports automatic quoting of database table and column names. A name enclosed within double curly brackets is treated as a table name, and a name enclosed within double square brackets is treated as a column name. They will be quoted according to the database driver being used:

Yii 2.0支持自动引用数据库的表名和列名。一个由双花括号括起来的命名视为表名,双方括号括起来的视为列名。其引用的结果取决于所使用的数据库驱动:

This feature is especially useful if you are developing an application that supports different DBMS.


用户及认证接口User and IdentityInterface

The CWebUser class in 1.1 is now replaced by [[yii\web\User]], and there is no more CUserIdentity class. Instead, you should implement the [[yii\web\IdentityInterface]] which is much more straightforward to implement. The advanced application template provides such an example.

1.1版本中的CWebUser现在被[[yii\web\User]]所取代,而且不再有CUserIdentity 类。更为直接的,通过实现[[yii\web\IdentityInterface]]接口。这在高级模板中有实例。

URL管理 URL Management

URL management is similar to 1.1. A major enhancement is that it now supports optional parameters. For example, if you have rule declared as follows, then it will match both post/popular and post/1/popular. In 1.1, you would have to use two rules to achieve the same goal.


More details in the Url manager docs.





与Composer整合 Integration with Composer

Yii is fully inegrated with the package manager for PHP named Composer that resolves dependencies, keeps your code up to date updating it semi-automatically and manages autoloading for third party libraries no matter which autoloading these are using.


In order to learn more refer to composer and installation sections of the guide.

Using Yii 1.1 and 2.x together

Check the guide on using Yii together with 3rd-Party Systems on this topic