intro-upgrade-from-v1.md 19.6 KB
Newer Older
Qiang Xue committed
1 2
Upgrading from Version 1.1
==========================
Qiang Xue committed
3

Carsten Brandt committed
4 5 6
There are many differences between versions 1.1 and 2.0 of Yii as the framework was completely rewritten for 2.0.
As a result, upgrading from version 1.1 is not as trivial as upgrading between minor versions. In this guide you'll
find the major differences between the two versions.
7

Larry Ullman committed
8 9 10
Please note that Yii 2.0 introduces more new features than are covered in this summary. It is highly recommended
that you read through the whole definitive guide to learn about them all. Chances are that
some features you previously had to develop for yourself are now part of the core code.
11 12 13 14 15


Installation
------------

Larry Ullman committed
16 17 18 19 20
Yii 2.0 fully embraces [Composer](https://getcomposer.org/), the de facto PHP package manager. Installation
of the core framework, as well as extensions, are handled through Composer. Please refer to
the [Starting from Basic App](start-basic.md) section to learn how to install Yii 2.0. If you want to
create new extensions, or turn your existing 1.1 extensions into 2.0-compatible extensions, please refer to
the [Creating Extensions](extend-creating-extensions.md) section of the guide.
Qiang Xue committed
21

22

Qiang Xue committed
23 24 25
PHP Requirements
----------------

Larry Ullman committed
26 27
Yii 2.0 requires PHP 5.4 or above, which is a huge improvement over PHP version 5.2 that is required by Yii 1.1.
As a result, there are many differences on the language level that you should pay attention to.
Qiang Xue committed
28
Below is a summary of the major changes regarding PHP:
29 30 31

- [Namespaces](http://php.net/manual/en/language.namespaces.php).
- [Anonymous functions](http://php.net/manual/en/functions.anonymous.php).
Qiang Xue committed
32 33 34
- Short array syntax `[...elements...]` is used instead of `array(...elements...)`.
- Short echo tags `<?=` are used in view files. This is safe to use starting from PHP 5.4.
- [SPL classes and interfaces](http://php.net/manual/en/book.spl.php).
35 36 37
- [Late Static Bindings](http://php.net/manual/en/language.oop5.late-static-bindings.php).
- [Date and Time](http://php.net/manual/en/book.datetime.php).
- [Traits](http://php.net/manual/en/language.oop5.traits.php).
Qiang Xue committed
38 39 40
- [intl](http://php.net/manual/en/book.intl.php). Yii 2.0 makes use of the `intl` PHP extension
  to support internationalization features.

Qiang Xue committed
41

Qiang Xue committed
42 43 44 45 46
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.
Larry Ullman committed
47 48 49 50 51
The naming scheme now follows the directory structure. For example, `yii\web\Request`
indicates that 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.)
Qiang Xue committed
52 53


Qiang Xue committed
54 55 56
Component and Object
--------------------

57
Yii 2.0 breaks the `CComponent` class in 1.1 into two classes: [[yii\base\Object]] and [[yii\base\Component]].
58
The [[yii\base\Object|Object]] class is a lightweight base class that allows defining [object properties](concept-properties.md)
59
via getters and setters. The [[yii\base\Component|Component]] class extends from [[yii\base\Object|Object]] and supports
60
[events](concept-events.md) and [behaviors](concept-behaviors.md).
Qiang Xue committed
61 62

If your class does not need the event or behavior feature, you should consider using
Qiang Xue committed
63
[[yii\base\Object|Object]] as the base class. This is usually the case for classes that represent basic
Qiang Xue committed
64 65 66 67 68 69
data structures.


Object Configuration
--------------------

70 71
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
72
it can be properly configured:
Qiang Xue committed
73

74
```php
Qiang Xue committed
75
class MyClass extends \yii\base\Object
Qiang Xue committed
76
{
Alexander Makarov committed
77
    public function __construct($param1, $param2, $config = [])
Qiang Xue committed
78
    {
79 80
        // ... initialization before configuration is applied

Qiang Xue committed
81 82 83 84 85 86
        parent::__construct($config);
    }

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

        // ... initialization after configuration is applied
Qiang Xue committed
89 90
    }
}
91
```
Alexander Makarov committed
92

93
In the above, the last parameter of the constructor must take a configuration array
Larry Ullman committed
94
that contains name-value pairs for initializing the properties at the end of the constructor.
95
You can override the [[yii\base\Object::init()|init()]] method to do initialization work that should be done after
Larry Ullman committed
96
the configuration has been applied.
Qiang Xue committed
97

Larry Ullman committed
98 99
By following this convention, you will be able to create and configure new objects
using a configuration array:
Qiang Xue committed
100

101
```php
Alexander Makarov committed
102
$object = Yii::createObject([
Qiang Xue committed
103 104 105
    'class' => 'MyClass',
    'property1' => 'abc',
    'property2' => 'cde',
Qiang Xue committed
106
], [$param1, $param2]);
107
```
Alexander Makarov committed
108

Larry Ullman committed
109
More details about configurations can be found in the [Object Configurations](concept-configurations.md) section.
110

Qiang Xue committed
111 112 113 114

Events
------

Larry Ullman committed
115
In Yii 1, events were created by defining an `on`-method (e.g., `onBeforeSave`). In Yii 2, you can now use any event name. You trigger an event by calling
Qiang Xue committed
116
the [[yii\base\Component::trigger()|trigger()]] method:
Qiang Xue committed
117

118
```php
Qiang Xue committed
119 120
$event = new \yii\base\Event;
$component->trigger($eventName, $event);
121
```
Qiang Xue committed
122

Larry Ullman committed
123
To attach a handler to an event, use the [[yii\base\Component::on()|on()]] method:
124 125

```php
Qiang Xue committed
126 127 128
$component->on($eventName, $handler);
// To detach the handler, use:
// $component->off($eventName, $handler);
129 130
```

Larry Ullman committed
131
There are many enhancements to the event features. For more details, please refer to the [Events](concept-events.md) section.
Qiang Xue committed
132

133

Qiang Xue committed
134 135
Path Aliases
------------
136

Larry Ullman committed
137 138
Yii 2.0 expands the usage of path aliases to both file/directory paths and URLs. Yii 2.0 also now requires
an alias name to start with the `@` character, to differentiate aliases from normal file/directory paths or URLs.
139
For example, the alias `@yii` refers to the Yii installation directory. Path aliases are
Qiang Xue committed
140
supported in most places in the Yii core code. For example, [[yii\caching\FileCache::cachePath]] can take
141 142
both a path alias and a normal directory path.

Larry Ullman committed
143 144
A path alias is also closely related to a class namespace. It is recommended that a path
alias be defined for each root namespace, thereby allowing you to use Yii the class autoloader without
145
any further configuration. For example, because `@yii` refers to the Yii installation directory,
Larry Ullman committed
146 147 148
a class like `yii\web\Request` can be autoloaded. If you use a third party library,
such as the Zend Framework, you may define a path alias `@Zend` that refers to that framework's installation
directory. Once you've done that, Yii will be able to autoload any class in that Zend Framework library, too.
149

Larry Ullman committed
150
More on path aliases can be found in the [Path Aliases](concept-aliases.md) section.
151

152

Qiang Xue committed
153 154
Views
-----
Qiang Xue committed
155

Larry Ullman committed
156 157 158 159
The most significant change about views in Yii 2 is that the special variable `$this` in a view no longer refers to
the current controller or widget. Instead, `$this` now refers to a *view* object, a new concept
introduced in 2.0. The *view* object is of type [[yii\web\View]], which represents the view part
of the MVC pattern. In you want to access the controller or widget in a view, you can use `$this->context`.
Qiang Xue committed
160

Larry Ullman committed
161 162
To render a partial view within another view, you use `$this->render()`, not `$this->renderPartial()`. The call to `render` also now has to be explicitly echoed, as the `render()` method returns the rendering
result, rather than directly displaying it. For example:
163 164 165 166 167

```php
echo $this->render('_item', ['item' => $item]);
```

168 169 170 171
Besides using PHP as the primary template language, Yii 2.0 is also equipped with official
support for two popular template engines: Smarty and Twig. The Prado template engine is no longer supported.
To use these template engines, you need to configure the `view` application component by setting the
[[yii\base\View::$renderers|View::$renderers]] property. Please refer to the [Template Engines](tutorial-template-engines.md)
Larry Ullman committed
172
section for more details.
173

Qiang Xue committed
174 175 176 177

Models
------

Larry Ullman committed
178 179
Yii 2.0 uses [[yii\base\Model]] as the base model, similar to `CModel` in 1.1.
The class `CFormModel` has been dropped entirely. Instead, in Yii 2 you should extend [[yii\base\Model]] to create a form model class.
180

181
Yii 2.0 introduces a new method called [[yii\base\Model::scenarios()|scenarios()]] to declare
Larry Ullman committed
182
supported scenarios, and to indicate under which scenario an attribute needs to be validated, can be considered as safe or not, etc. For example:
183

184
```php
185 186
public function scenarios()
{
Alexander Makarov committed
187 188 189 190
    return [
        'backend' => ['email', 'role'],
        'frontend' => ['email', '!name'],
    ];
191
}
192
```
Alexander Makarov committed
193

Larry Ullman committed
194 195 196
In the above, two scenarios are declared: `backend` and `frontend`. For the `backend` scenario, both the
`email` and `role` attributes are safe, and can be massively assigned. For the `frontend` scenario,
`email` can be massively assigned while `role` cannot. Both `email` and `role` should be validated using rules.
197

Larry Ullman committed
198
The [[yii\base\Model::rules()|rules()]] method is still used to declare the validation rules. Note that due to the introduction of [[yii\base\Model::scenarios()|scenarios()]], there is no longer an `unsafe` validator.
199

Paul K committed
200
In most cases, you do not need to override [[yii\base\Model::scenarios()|scenarios()]]
Larry Ullman committed
201
if the [[yii\base\Model::rules()|rules()]] method fully specifies the scenarios that will exist, and if there is no need to declare
202
`unsafe` attributes.
203

Larry Ullman committed
204
To learn more details about models, please refer to the [Models](basic-models.md) section.
205

206

Qiang Xue committed
207 208 209
Controllers
-----------

Larry Ullman committed
210 211
Yii 2.0 uses [[yii\web\Controller]] as the base controller class, similar to `CWebController` in Yii 1.1.
[[yii\base\Action]] is the base class for action classes.
212

Larry Ullman committed
213 214
The most obvious impact of these changes on your code is that a controller action should return the content
that you want to render instead of echoing it:
215 216 217 218 219 220 221 222 223 224 225 226 227

```php
public function actionView($id)
{
    $model = \app\models\Post::findOne($id);
    if ($model) {
        return $this->render('view', ['model' => $model]);
    } else {
        throw new \yii\web\NotFoundHttpException;
    }
}
```

Larry Ullman committed
228
Please refer to the [Controllers](structure-controllers.md) section for more details about controllers.
229

230

231 232 233
Widgets
-------

Larry Ullman committed
234
Yii 2.0 uses [[yii\base\Widget]] as the base widget class, similar to `CWidget` in Yii 1.1.
235

Larry Ullman committed
236 237 238
To get better support for the framework in IDEs, Yii 2.0 introduces a new syntax for using widgets. The static methods
[[yii\base\Widget::begin()|begin()]], [[yii\base\Widget::end()|end()]], and [[yii\base\Widget::widget()|widget()]]
have been introduced, to be used like so:
239 240

```php
Qiang Xue committed
241 242 243
use yii\widgets\Menu;
use yii\widgets\ActiveForm;

244
// Note that you have to "echo" the result to display it
Qiang Xue committed
245
echo Menu::widget(['items' => $items]);
246

247
// Passing an array to initialize the object properties
Qiang Xue committed
248
$form = ActiveForm::begin([
249 250
    'options' => ['class' => 'form-horizontal'],
    'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
Alexander Makarov committed
251
]);
Qiang Xue committed
252 253
... form input fields here ...
ActiveForm::end();
254 255
```

Larry Ullman committed
256
Please refer to the [Widgets](structure-widgets.md) section for more details.
257

258

Qiang Xue committed
259 260 261
Themes
------

Larry Ullman committed
262
Themes work completely differently in 2.0. They are now based on a path mapping mechanism that maps a source
263
view file path to a themed view file path. For example, if the path map for a theme is
Larry Ullman committed
264
`['/web/views' => '/web/themes/basic']`, then the themed version for the view file
265
`/web/views/site/index.php` will be `/web/themes/basic/site/index.php`. For this reason, themes can now
Larry Ullman committed
266
be applied to any view file, even a view rendered outside of the context of a controller or a widget.
267

Larry Ullman committed
268
Also, there is no more `CThemeManager` component. Instead, `theme` is a configurable property of the `view`
269 270
application component.

Larry Ullman committed
271
Please refer to the [Theming](tutorial-theming.md) section for more details.
272

273

Qiang Xue committed
274 275 276
Console Applications
--------------------

277
Console applications are now organized as controllers, like Web applications. Console controllers
Larry Ullman committed
278
should extend from [[yii\console\Controller]], similar to `CConsoleCommand` in 1.1.
279

280 281 282 283
To run a console command, use `yii <route>`, 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, while named arguments are parsed according to
the declarations in [[yii\console\Controller::options()]].
284 285 286

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

287
Please refer to the [Console Commands](tutorial-console.md) section for more details.
288

289

Qiang Xue committed
290 291 292
I18N
----

Larry Ullman committed
293
Yii 2.0 removes the built-in date formatter and number formatter pieces in favor of the [PECL intl PHP module](http://pecl.php.net/package/intl).
Qiang Xue committed
294

295
Message translation is now performed via the `i18n` application component.
Larry Ullman committed
296
This component manages a set of message sources, which allows you to use different message
297 298
sources based on message categories.

Larry Ullman committed
299
Please refer to the [Internationalization](tutorial-i18n.md) section for more details.
300 301 302 303 304


Action Filters
--------------

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

309
```php
310 311
public function behaviors()
{
Alexander Makarov committed
312 313
    return [
        'access' => [
314
            'class' => 'yii\filters\AccessControl',
Alexander Makarov committed
315 316
            'rules' => [
                ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
317 318 319
            ],
        ],
    ];
320
}
321
```
Alexander Makarov committed
322

323
Please refer to the [Filtering](runtime-filtering.md) section for more details.
Qiang Xue committed
324 325 326 327 328


Assets
------

329
Yii 2.0 introduces a new concept called *asset bundle* that replaces the script package concept found in Yii 1.1.
330 331

An asset bundle is a collection of asset files (e.g. JavaScript files, CSS files, image files, etc.)
332 333 334
within 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 make
the assets in that bundle accessible via the Web. Unlike in Yii 1, the page registering the bundle will automatically
335
contain the references to the JavaScript and CSS files specified in that bundle.
336

337
Please refer to the [Managing Assets](output-assets.md) section for more details.
338

339 340 341

Helpers
-------
Qiang Xue committed
342

343
Yii 2.0 introduces many commonly used static helper classes, including.
344

345 346 347 348 349 350
* [[yii\helpers\Html]]
* [[yii\helpers\ArrayHelper]]
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
351

352
Please refer to the [Helper Overview](helper-overview.md) section for more details.
353 354 355

Forms
-----
Qiang Xue committed
356

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

362
```php
363
<?php $form = yii\widgets\ActiveForm::begin(); ?>
364 365 366 367 368
    <?= $form->field($model, 'username') ?>
    <?= $form->field($model, 'password')->passwordInput() ?>
    <div class="form-group">
        <?= Html::submitButton('Login') ?>
    </div>
369
<?php yii\widgets\ActiveForm::end(); ?>
370
```
Alexander Makarov committed
371

372 373
Please refer to the [Creating Forms](input-forms.md) section for more details.

374

Qiang Xue committed
375 376 377
Query Builder
-------------

378
In 1.1, query building was scattered among several classes, including `CDbCommand`,
379
`CDbCriteria`, and `CDbCommandBuilder`. Yii 2.0 represents a DB query in terms of a [[yii\db\Query|Query]] object
380
that can be turned into a SQL statement with the help of [[yii\db\QueryBuilder|QueryBuilder]] behind the scene.
381
For example:
382

383
```php
384
$query = new \yii\db\Query();
385
$query->select('id, name')
386
      ->from('user')
387 388 389 390 391
      ->limit(10);

$command = $query->createCommand();
$sql = $command->sql;
$rows = $command->queryAll();
392
```
Alexander Makarov committed
393

394
Best of all, such query building methods can also be used when working with [Active Record](db-active-record.md).
Qiang Xue committed
395

396
Please refer to the [Query Builder](db-query-builder.md) section for more details.
Qiang Xue committed
397

398

399 400
Active Record
-------------
401

Larry Ullman committed
402
Yii 2.0 introduces a lot of changes to [Active Record](db-active-record.md). The two most obvious ones involve
403
query building and relational query handling.
404

Larry Ullman committed
405 406
The `CDbCriteria` class in 1.1 is replaced by [[yii\db\ActiveQuery]] in Yii 2. That class extends from [[yii\db\Query]], and thus
inherits all query building methods. You call [[yii\db\ActiveRecord::find()]] to start building a query:
407

408
```php
Larry Ullman committed
409
// To retrieve all *active* customers and order them by their ID:
410
$customers = Customer::find()
411 412 413
    ->where(['status' => $active])
    ->orderBy('id')
    ->all();
414
```
Alexander Makarov committed
415

Larry Ullman committed
416
To declare a relation, simply define a getter method that returns an [[yii\db\ActiveQuery|ActiveQuery]] object.
417 418
The property name defined by the getter represents the relation name. For example, the following code declares
an `orders` relation (in 1.1, you would have to declare relations in a central place `relations()`):
419

420
```php
421 422 423 424 425 426 427
class Customer extends \yii\db\ActiveRecord
{
    public function getOrders()
    {
        return $this->hasMany('Order', ['customer_id' => 'id']);
    }
}
428
```
429

Larry Ullman committed
430 431
Now you can use `$customer->orders` to access a customer's orders from the related table. You can also use the following code
to perform an on-the-fly relational query with a customized query condition:
432

433 434 435
```php
$orders = $customer->getOrders()->andWhere('status=1')->all();
```
436

437
When eager loading a relation, Yii 2.0 does it differently from 1.1. In particular, in 1.1 a JOIN query
Larry Ullman committed
438
would be created to select both the primary and the relational records. In Yii 2.0, two SQL statements are executed
439 440
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.
441

442
Instead of returning [[yii\db\ActiveRecord|ActiveRecord]] objects, you may chain the [[yii\db\ActiveQuery::asArray()|asArray()]]
Larry Ullman committed
443
method when building a query to return a large number of records. This will cause the query result to be returned
444
as arrays, which can significantly reduce the needed CPU time and memory if large number of records . For example,
445

446
```php
447
$customers = Customer::find()->asArray()->all();
448
```
Alexander Makarov committed
449

450 451 452 453 454 455 456 457 458 459 460
Another change is that you can't define attribute default values through public properties anymore.
If you need those, you should set them in the init method of your record class.

```php
public function init()
{
    parent::init();
    $this->status = self::STATUS_NEW;
}
```

461 462 463
There where some problems with overriding the constructor of an ActiveRecord class in 1.1. These are not present in
version 2.0 anymore. Note that when adding parameters to the constructor you might have to override [[yii\db\ActiveRecord::instantiate()]].

464
There are many other changes and enhancements to Active Record. Please refer to
465
the [Active Record](db-active-record.md) section for more details.
466 467


468 469
User and IdentityInterface
--------------------------
Qiang Xue committed
470

471 472
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
Larry Ullman committed
473 474 475
is much more straightforward to use. The advanced application template provides such an example.

Please refer to the [Authentication](security-authentication.md), [Authorization](security-authorization.md), and [Advanced Application Technique](tutorial-advanced-app.md) sections for more details.
476 477


Qiang Xue committed
478 479 480
URL Management
--------------

Carsten Brandt committed
481 482
URL management in Yii 2 is similar to that in 1.1. A major enhancement is that URL management now supports optional
parameters. For example, if you have a rule declared as follows, then it will match
Larry Ullman committed
483
both `post/popular` and `post/1/popular`. In 1.1, you would have had to use two rules to achieve
484 485
the same goal.

486
```php
Alexander Makarov committed
487
[
488 489 490
    'pattern' => 'post/<page:\d+>/<tag>',
    'route' => 'post/index',
    'defaults' => ['page' => 1],
Alexander Makarov committed
491
]
492
```
Alexander Makarov committed
493

Larry Ullman committed
494
Please refer to the [Url manager docs](url.md) section for more details.
495 496 497 498

Using Yii 1.1 and 2.x together
------------------------------

Larry Ullman committed
499
If you have legacy Yii 1.1 code that you want to use together with Yii 2.0, please refer to
500
the [Using Yii 1.1 and 2.0 Together](extend-using-v1-v2.md) section.
501