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


命名空间(Namespace)

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的类装载机制,可以在未显示包含类文件的情况下使用任意的核心类。


组件(Component)和对象(Object)

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:

[[yii\base\Object|Object]]对配置对象引入了一个规范的方法。其后代类可以在需要的情况下通过如下的方式声明一个构造函数,那么该类就可以被正确的配置:

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.

上面代码中,构造函数据的最后一个形参必须是接收一下包含键值对的配置数组,用于在初始化类的属性。可以重载[[yii\base\Object::init()|init()]]方法以在配置后执行初始化工作。

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

按照如下的约定,可以用配置数组创建一个新对象:


事件(Events)

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:

在绑定一个handler时,可以关联一些参数,以便于handler在后续处理时可以通过事件参数访问:

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

由于这一改变,现在可以使用一些“全局”的事件。只需简单地触发和绑定一个事件到application实例上:

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可以自动加载该库中的所有类。


视图(View)

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:

由于可以通过应用的“view”组件访问视图对象,因此可以在任意代码中渲染一个视图文件,而不再局限于controller或widget中。如下:

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]]属性以使用其他模板引擎。


模型(Models)

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.

现在,一个模型是与其一个表单通过其[[yii\base\Model::formName()|formName()]]方法返回的表单名紧密关联的。这通常用于收集用户在HTML表单上的输入。之前在1.1版本中,通常以硬编码为类名的方式设计模型。

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.

如果一个模型仅有一个应用场景,这很常见,则需一定非要重载[[yii\base\Model::scenarios()|scenarios()]],然后一切都会现原先在1.1版本中的方式一样。


控制器(Controllers)

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

$this->render(…);.

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


挂件Widgets

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.

原先在1.1版本中,需要在CBaseController类的beginWidget(),endWidget()和widget()方法中将挂件的类名以字符串的形式传入。而2.0版本使用的方法对于IDE而言,更为友好。


主题(Themes)

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.

也不在有CThemeManager,相应地,theme成为应用的view组件的一个可设置的属性。


命令行应用(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.

命令行应用现和Web应用一样由控件器组成。事实上,命令行控制器和Web控制器共用相同的控制器基类。

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支持自动从注释块中生成一个命令的帮助信息。


图际化(I18N)

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.

消息翻译仍通过应用的“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.


资源(Assets)

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]])来克服这个困难。


ActiveForm

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]]搭配。


ActiveRecord

[[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.

可以使用$customer->orders以访问用户的订单。还可以用$customer->getOrders()->andWhere(‘status=1’)->all()来实现一个基于自定义条件的实时的关系查询。

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:

如果不想返回一个ActiveRecord对象,可以调用[[yii\db\ActiveQuery::asArray()|ActiveQuery::asArray()]]以返回一个数组。这会提高效率,特别是需要返回大量记录的时候:

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.

默认地,ActiveRecord现在只保存改变了的属性值。在1.1版本中,当调用save()时,所有的属性都被保存到数据库中,而不管是属性值是否有改变,除非显式地列出要保存的属性。

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

查询范围(Scope)现在不再定义于模型中,而是定义于自定义的[[yii\db\ActiveQuery|ActiveQuery]]类中。

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.

这个特性在开发支持各种不同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.

URL管理与1.1版本一样,一个主要的加强是对于可选参数的支持。比如,如下规则匹配post/popular和post/1/popular。在1.1版本中,需要写2个规则来达到这一目的。

More details in the Url manager docs.


Response

TBD

Extensions

TBD


与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.

Yii完全地与Composer这一PHP包管理器整合,这解决了依赖问题,并保持代码不过时,半自动地更新、管理第三方库自动加载不管理其使用的是何种自动加载机制。

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