標籤:

yii 2 相比yii 1.1.x 有什麼變化?

yii 2 相比yii 1.1.x ,有什麼優點和變化 ?選擇時應該注意什麼?


更新:重新寫了一個,改正了一些書寫錯誤,並進行排版,更新的版本在

《深入理解Yii2.0》附錄1:Yii2.0 對比 Yii1.1 的重大改進

---------------------------

我自己翻的官方升級文檔,供參考:

In this chapter, we list the major changes introduced in Yii 2.0
since version 1.1. We hope this list will make it easier for you to
upgrade from Yii 1.1 and quickly master Yii 2.0 based on your existing
Yii knowledge.

本章將列出自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., yiiwebRequest. The 「C」 prefix is no longer used in class names. The naming of the namespaces follows the directory structure. For example, yiiwebRequest 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最明顯的改變是對命名空間的使用。幾乎所有的核心類都使用了命名空間,比如yiiwebRequest。同時,類名前不再使用「C」前綴。命名空間的命名遵循目錄結構,如yiiwebRequest代表的相應類文件是位於Yii 框架的目錄下的 web/Request.php。由於Yii的類裝載機制,可以在未顯示包含類文件的情況下使用任意的核心類。

組件(Component)和對象(Object)

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

Yii 2.0將1.1版本中的CComponent類拆分成兩個類:[[yiiaseObject]] 和
[[yiiaseComponent]]。其中,[[yiiaseObject|Object]]類是一個輕量級的基類,它通過getter
和setter提供了定義類屬性(property)的方法。[[yiiaseComponent|Component]]繼承自[[yii
aseObject|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 [[yiiaseObject|Object]] class introduces a uniform way of
configuring objects. Any descendant class of [[yiiaseObject|Object]]
should declare its constructor (if needed) in the following way so that
it can be properly configured:

[[yiiaseObject|Object]]對配置對象引入了一個規範的方法。其後代類可以在需要的情況下通過如下的方式聲明一個構造函數,那麼該類就可以被正確的配置:

class MyClass extends yiiaseObject
{
function __construct($param1, $param2, $config = [])
{
// ... initialization before configuration is applied

parent::__construct($config);
}

public function init ()
{
parent::init();

// ... initialization after configuration is applied
}
}

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
[[yiiaseObject::init()|init()]] method to do initialization work that
should be done after the configuration is applied.

上面代碼中,構造函數據的最後一個形參必須是接收一下包含鍵值對的配置數組,用於在初始化類的屬性。可以重載[[yiiaseObject::init()|init()]]方法以在配置後執行初始化工作。

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

按照如下的約定,可以用配置數組創建一個新對象:

$object = Yii::createObject([
class =&> MyClass,
property1 =&> abc,
property2 =&> cde,
], $param1, $param2);

事件(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方法:

$component-&>on($eventName, $handler);
// To detach the handler, use:
// $component-&>off($eventName, $handler);

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在後續處理時可以通過事件參數訪問:

$component-&>on($eventName, $handler, $params);

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

由於這一改變,現在可以使用一些「全局」的事件。只需簡單地觸發和綁定一個事件到application實例上:

Yii::$app-&>on($eventName, $handler);
....
// this will trigger the event and cause $handler to be invoked.
Yii::$app-&>trigger($eventName);

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

如果需要處理一個類的所有實例上的事件,可以使用如下方法綁定事件:

Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
Yii::trace(get_class($event-&>sender) . is inserted.);
});

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擴大了對路徑別名的使用,包含文件目錄和URL。一個別名需以@字元開頭,以便與文件目錄路徑和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 yiiwebRequest 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的類裝載機制載入類而不需要額外的配置。比如,由於@yii代表了Yii的安裝路徑,一個諸如yiiwebRequest的類就可以被Yii自動裝載。如果使用了Zend Framework等第三方庫,可以定義一個@Zend的路徑別名來指向其安裝目錄,那麼Yii可以自動載入該庫中的所有類。

視圖(View)

Yii 2.0 introduces a [[yiiwebView|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引入了一個[[yiiwebView|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中。如下:

$content = Yii::$app-&>view-&>renderFile($viewFile, $params);
// You can also explicitly create a new View instance to do the rendering
// $view = new View;
// $view-&>renderFile($viewFile, $params);

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

同時,Yii 2.0中不再有CClientScript,[[yiiwebView|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
[[yiiwebView::$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視圖。還可以通過設置[[yiiwebView::$renderers|View::$renderers]]屬性以使用其他模板引擎。

模型(Models)

A model is now associated with a form name returned by its
[[yiiaseModel::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.

現在,一個模型是與其一個表單通過其[[yiiaseModel::formName()|formName()]]方法返回的表單名緊密關聯的。這通常用於收集用戶在HTML表單上的輸入。之前在1.1版本中,通常以硬編碼為類名的方式設計模型。

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

引入了[[yiiaseModel::load()|load()] 和 [[yiiaseModel::loadMultiple()|Model::loadMultiple()]]兩個新的方法用於簡化將用戶輸入的數據填充到一個模型中。比如:

$model = new Post;
if ($model-&>load($_POST)) {...}
// which is equivalent to:
if (isset($_POST[Post])) {
$model-&>attributes = $_POST[Post];
}

$model-&>save();

$postTags = [];
$tagsCount = count($_POST[PostTag]);
while ($tagsCount-- &> 0) {
$postTags[] = new PostTag([post_id =&> $model-&>id]);
}
Model::loadMultiple($postTags, $_POST);

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

Yii
2.0引入了[[yiiaseModel::scenarios()|scenarios()]]新方法,用以聲明哪些屬性
(attributes)在哪些場景下需要驗證。子類需重載[[yiiaseModel::scenarios()|scenarios()]]方
法,並返一個包含場景及相應需要驗證的屬性的列表,以供調用[[yiiaseModel::validate()|validate()]]時使
用。如:

public function scenarios()
{
return [
backend =&> [email, role],
frontend =&> [email, !name],
];
}

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
[[yiiaseModel::scenarios()|scenarios()]] and the name is not prefixed
with !, it is considered safe.

同時,這個方法也明確了哪些屬性是安全的,哪些是不安全的。在實際操作中,給定一個場景,如果一個屬性出現在[[yiiaseModel::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 [[yiiaseModel::scenarios()|scenarios()]], and everything
will still work like the 1.1 way.

如果一個模型僅有一個應用場景,這很常見,則需一定非要重載[[yiiaseModel::scenarios()|scenarios()]],然後一切都會現原先在1.1版本中的方式一樣。


控制器(Controllers)

The [[yiiaseController::render()|render()]] and
[[yiiaseController::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(...);.

[[yiiaseController::render()|render()]]和[[yiiase
Controller::renderPartial()|renderPartial()]]方法現在返回渲染後的結果,而不再是直接發送出去給用
戶。因此,需要顯式的用echo將結果發送出去。如:echo $this-&>render(...);。

掛件Widgets

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

在2.0版本中,使用掛件將更為直接。主要使用[[yiiaseWidget|Widget]]類的[[yiiase
Widget::begin()|begin()]],[[yiiaseWidget::end()|end()]] 和
[[yiiaseWidget::widget()|widget()]]方法。如:

// Note that you have to "echo" the result to display it
echo yiiwidgetsMenu::widget([items =&> $items]);

// Passing an array to initialize the object properties
$form = yiiwidgetsActiveForm::begin([
options =&> [class =&> form-horizontal],
fieldConfig =&> [inputOptions =&> [class =&> input-xlarge]],
]);
... form inputs here ...
yiiwidgetsActiveForm::end();

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 & command to execute a console command, where & 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 &命令執行一個命令行命令, &代表一個控制項器路由(如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 [[yiiaseActionFilter]] 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 [[yiiwebAccessControl]] filter, you should have
the following code in a controller:

Action過濾器已經改由行為(behavior)來實現。可以通過繼承 [[yiiaseActionFilter]]
來定義新的過濾器。使用一個過濾器,可以將一個過濾器類作為行為綁定到一個控制器。如,要使用[[yiiwebAccessControl]]過濾器
可以在控制器中進行如下編碼:

public function behaviors()
{
return [
access =&> [
class =&> yiiwebAccessControl,
rules =&> [
[allow =&> true, actions =&> [admin], roles =&> [@]],
),
),
);
}

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 [[yiiwebAssetBundle]]. By
registering an asset bundle via [[yiiwebAssetBundle::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文件、圖片等。每個資源包由一個繼承自[[yiiweb
AssetBundle]]的類來表徵。使用[[yiiwebAssetBundle::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
[[yiihelpersHtml|Html]], [[yiihelpersArrayHelper|ArrayHelper]],
[[yiihelpersStringHelper|StringHelper]].
[[yiihelpersFileHelper|FileHelper]], [[yiihelpersJson|Json]],
[[yiihelpersSecurity|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引入了諸多常用的靜態工具類,如[[yiihelpersHtml|Html]],[[yiihelpers
ArrayHelper|ArrayHelper]],[[yiihelpersStringHelper|StringHelper]],
[[yiihelpersFileHelper|FileHelper]], [[yiihelpersJson|Json]],
[[yiihelpersSecurity|Security]]這些類都設計成易於繼承,儘管靜態類由於固定的類名引用而通常不易繼承。但是Yii
2.0引入了類映射(利用[[Yii::$classMap]])來克服這個困難。

ActiveForm

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

Yii 2.0引入了field的概念用於通過[[yiiwidgetsActiveForm]]創建的表單。一個欄位就是
一個包含了一個標籤、一個input控制項和一個錯誤信息/提示文本的容器,以[[yiiwidgets
ActiveField|ActiveField]]類對象表示。使用欄位,可以更簡潔的創建表單:

&
&field($model, username) ?&>
&field($model, password)-&>passwordInput() ?&>
&
&
& &

查詢構建器(Query Builder)

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

在1.1版本中,資料庫查詢的構建被分散到幾個類中,如CDbCommand,CDbCriteria和CDbCommandBuilder。Yii 2.0使用 [[yiidbQuery|Query]]表示資料庫查詢,並使用[[yiidbQueryBuilder|QueryBuilder]]從query對象生成SQL語句。如,

$query = new yiidbQuery;
$query-&>select(id, name)
-&>from(tbl_user)
-&>limit(10);

$command = $query-&>createCommand();
$sql = $command-&>sql;
$rows = $command-&>queryAll();

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

更難得的,這個構建查詢的方法可以與下面的[[yiidbActiveRecord|ActiveRecord]]搭配。

ActiveRecord

[[yiidbActiveRecord|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
[[yiidbActiveQuery|ActiveQuery]] object. For example, the following
method declares an 「orders」 relation:

[[yiidbActiveRecord|ActiveRecord]]在Yii 2.0中經歷了顯著的變更。最為重要的方面是關聯ActiveRecord查詢。在1.1版本中,需要在relations() 方法中聲明關係。而在2.0中,改為由一個返回[[yiidbActiveQuery|ActiveQuery]] 對象的getter方法來完成。比如,以下的方法聲明了一個關於訂單的關係:

class Customer extends yiidbActiveRecord
{
public function getOrders()
{
return $this-&>hasMany(Order, [customer_id =&> id]);
}
}

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 [[yiidbActiveRecord::find()|find()]] method:

Yii 2.0不再使用model()方法來執行查詢,而改用[[yiidbActiveRecord::find()|find()]]方法:

// to retrieve all *active* customers and order them by their ID:
$customers = Customer::find()
-&>where([status =&> $active])
-&>orderBy(id)
-&>all();
// return the customer whose PK is 1
$customer = Customer::find(1);

The [[yiidbActiveRecord::find()|find()]] method returns an instance
of [[yiidbActiveQuery|ActiveQuery]] which is a subclass of
[[yiidbQuery]]. Therefore, you can use all query methods of
[[yiidbQuery]].

[[yiidbActiveRecord::find()|find()]]方法返回一個[[yiidb
ActiveQuery|ActiveQuery]]實例,注意該[[yiidbActiveQuery|ActiveQuery]]是[[yii
dbQuery]]的子類。因此,可以對其使用[[yiidbQuery]]的所有查詢方法。

Instead of returning ActiveRecord objects, you may call
[[yiidbActiveQuery::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對象,可以調用[[yiidbActiveQuery::asArray()|ActiveQuery::asArray()]]以返回一個數組。這會提高效率,特別是需要返回大量記錄的時候:

$customers = Customer::find()-&>asArray()-&>all();

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 [[yiidbActiveQuery|ActiveQuery]] class instead of model directly.

查詢範圍(Scope)現在不再定義於模型中,而是定義於自定義的[[yiidbActiveQuery|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支持自動引用資料庫的表名和列名。一個由雙花括弧括起來的命名視為表名,雙方括弧括起來的視為列名。其引用的結果取決於所使用的資料庫驅動:

$command = $connection-&>createCommand(SELECT [[id]] FROM {{posts}});
echo $command-&>sql; // MySQL: SELECT `id` FROM `posts`

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 [[yiiwebUser]], and there is no more CUserIdentity
class. Instead, you should implement the [[yiiwebIdentityInterface]]
which is much more straightforward to implement. The advanced
application template provides such an example.

1.1版本中的CWebUser現在被[[yiiwebUser]]所取代,而且不再有CUserIdentity 類。更為直接的,通過實現[[yiiwebIdentityInterface]]介面。這在高級模板中有實例。

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個規則來達到這一目的。

[
pattern =&> post/&

/&,
route =&> post/index,
defaults =&> [page =&> 1],
]

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


本想仔細回答一下這個問題,但看到有比較好的回答了,而我又太懶,還是作罷。


門外漢開個頭(用過一小段時間1以及看2發布了看了點核碼)

變化及優點:

大致思路不會變,開發流程變化也不是很大。

有變化的是

1、yii2帶入的PHP5.4的特性,引入了namespace解決命名衝突,因此基類不會再C字開頭了

2、不再所有類都繼承自組件Component,而是選擇繼承object和component(也繼承自object,但帶有事件功能、以及用於擴展的Behavior功能)

3、更加的MVC,原先的view層其實基本算是controller直接include進來的,現在有了view的類用來控制,因此View層在使用Controller帶來的參數的方式稍有不同。

4、yii2分基本版(看上去和1差不多)和高級版(分前台和後台),高級版更加適合開發大型項目。

5、其他的都是細節方面的變化,比如塊賦值(基本用於收集表單數據)更加方便了。安裝完畢界面就自帶bootstrap風格了,等等等等。

當然還有許多其他的特性,可以直接參看yii在git上更新的文檔:

yii2/docs/guide/upgrade-from-v1.md at master 路 yiisoft/yii2 路 GitHub

--update--

1、加入了Dependency Injection(依賴注入,理論可以看經典翻譯文IoC容器和依賴注入模式(轉)-redcoffee-ChinaUnix博客,yii的具體實現看/vendor/yiisoft/yii2/di下的container和instance就行),以後創建對象時基本都可以用容器的get方法替代new了,很不錯很贊喲~

選擇:

如果你急於馬上開啟一個項目的話 用1.1.X,因為2的正式版估計還有好多個月吧。

如果你是帶著學習研究的態度的,直接從2的beta版開始看吧,和正式版不會變化很大。

純門外漢瞎搭,大神路過發現有不對之處隨意拍磚:P


推薦一個博客地址,關於教程的:http://www.fancyecommerce.com/


推薦閱讀:

PHP框架中thinkPHP和Swoole有什麼區別?
Yii測試沒找到PHPUnit_Extensions_Database_TestCase?(已解決)
如何開發 PHP 擴展?PHP 擴展應該注意些什麼?
PHP如何模擬登錄學校個人門戶?
新人剛接觸 PHP,哪種框架比較容易上手?

TAG:PHP框架 | Yii |