upgrade-from-v1.md 17.9 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8
Upgrading from Yii 1.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.


Qiang Xue committed
9 10 11 12 13 14 15
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.
ploaiza committed
16
You can use any core class without explicitly including that class file, thanks to the Yii
Qiang Xue committed
17 18 19
class loader.


Qiang Xue committed
20 21 22 23 24 25 26 27 28
Component and Object
--------------------

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

If your class does not need the event or behavior feature, you should consider using
br0sk committed
29
`Object` as the base class. This is usually the case for classes that represent basic
Qiang Xue committed
30 31
data structures.

32 33
More details about Object and component can be found in the [Basic concepts section](basics.md).

Qiang Xue committed
34 35 36 37

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

38 39 40
The `Object` class introduces a uniform way of configuring objects. Any descendant class
of `Object` should declare its constructor (if needed) in the following way so that
it can be properly configured:
Qiang Xue committed
41

42
```php
Qiang Xue committed
43
class MyClass extends \yii\base\Object
Qiang Xue committed
44
{
Alexander Makarov committed
45
    public function __construct($param1, $param2, $config = [])
Qiang Xue committed
46
    {
47 48
        // ... initialization before configuration is applied

Qiang Xue committed
49 50 51 52 53 54
        parent::__construct($config);
    }

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

        // ... initialization after configuration is applied
Qiang Xue committed
57 58
    }
}
59
```
Alexander Makarov committed
60

61 62 63 64
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 `init()` method to do initialization work that should be done after
the configuration is applied.
Qiang Xue committed
65

66 67
By following this convention, you will be able to create and configure a new object
using a configuration array like the following:
Qiang Xue committed
68

69
```php
Alexander Makarov committed
70
$object = Yii::createObject([
Qiang Xue committed
71 72 73
    'class' => 'MyClass',
    'property1' => 'abc',
    'property2' => 'cde',
Alexander Makarov committed
74
], $param1, $param2);
75
```
Alexander Makarov committed
76

77 78
More on configuration can be found in the [Basic concepts section](basics.md).

Qiang Xue committed
79 80 81 82 83 84 85 86

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:

87
```php
Qiang Xue committed
88 89 90
$component->on($eventName, $handler);
// To detach the handler, use:
// $component->off($eventName, $handler);
91
```
Alexander Makarov committed
92

Qiang Xue committed
93 94 95 96

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:

97
```php
Qiang Xue committed
98
$component->on($eventName, $handler, $params);
99
```
Alexander Makarov committed
100

Qiang Xue committed
101 102 103 104

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

105
```php
Qiang Xue committed
106 107 108 109
Yii::$app->on($eventName, $handler);
....
// this will trigger the event and cause $handler to be invoked.
Yii::$app->trigger($eventName);
110
```
Qiang Xue committed
111

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

```php
Qiang Xue committed
115
Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
116 117 118 119 120
	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.
Qiang Xue committed
121

122 123 124
See [Event handling section](events.md) for more details.


125 126 127 128 129 130 131 132 133 134
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.

Path alias is also closely related with class namespaces. It is recommended that a path
ploaiza committed
135
alias be defined for each root namespace so that you can use Yii the class autoloader without
136 137
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
138
such as Zend Framework, you may define a path alias `@Zend` which refers to its installation
ploaiza committed
139
directory and Yii will be able to autoload any class in this library.
140

141 142
More on path aliases can be found in the [Basic concepts section](basics.md).

143

Qiang Xue committed
144 145 146
View
----

ploaiza committed
147
Yii 2.0 introduces a `View` class to represent the view part of the MVC pattern.
Qiang Xue committed
148 149 150 151 152 153 154 155 156 157
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.

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:

158
```php
Qiang Xue committed
159 160 161 162
$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);
163
```
Alexander Makarov committed
164

Qiang Xue committed
165 166 167 168

Also, there is no more `CClientScript` in Yii 2.0. The `View` class has taken over its role
with significant improvements. For more details, please see the "assets" subsection.

169 170
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
Qiang Xue committed
171
no longer supported. To use these template engines, you just need to use `tpl` as the file
172
extension for your Smarty views, or `twig` for Twig views. You may also configure the
173 174
`View::renderers` property to use other template engines. See [Using template engines](template.md) section
of the guide for more details.
175

176 177
See [View section](view.md) for more details.

Qiang Xue committed
178 179 180 181

Models
------

ploaiza committed
182
A model is now associated with a form name returned by its `formName()` method. This is
183 184 185
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.

186 187 188 189 190 191 192 193 194 195 196 197 198
A new methods called `load()` and `Model::loadMultiple()` is introduced to simplify the data population from user inputs
to a model. For example,

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

$model->save();

Alexander Makarov committed
199
$postTags = [];
200
$tagsCount = count($_POST['PostTag']);
201
while ($tagsCount-- > 0) {
Alexander Makarov committed
202
    $postTags[] = new PostTag(['post_id' => $model->id]);
203 204 205
}
Model::loadMultiple($postTags, $_POST);
```
206 207 208 209 210 211

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

212
```php
213 214
public function scenarios()
{
Alexander Makarov committed
215 216 217 218
    return [
        'backend' => ['email', 'role'],
        'frontend' => ['email', '!name'],
    ];
219
}
220
```
Alexander Makarov committed
221

222 223 224 225 226 227 228 229 230 231

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

Because of the above change, Yii 2.0 no longer has "safe" and "unsafe" validators.

If your model only has one scenario (very common), you do not have to overwrite `scenarios()`,
and everything will still work like the 1.1 way.

232 233
To learn more about Yii 2.0 models refer to [Models](model.md) section of the guide.

234

Qiang Xue committed
235 236 237
Controllers
-----------

238 239 240
The `render()` and `renderPartial()` methods now return the rendering results instead of directly
sending them out. You have to `echo` them explicitly, e.g., `echo $this->render(...);`.

241
To learn more about Yii 2.0 controllers refer to [Controller](controller.md) section of the guide.
242

243

244 245 246 247 248 249 250 251
Widgets
-------

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

```php
// Note that you have to "echo" the result to display it
Alexander Makarov committed
252
echo \yii\widgets\Menu::widget(['items' => $items]);
253

254
// Passing an array to initialize the object properties
Alexander Makarov committed
255 256 257 258
$form = \yii\widgets\ActiveForm::begin([
	'options' => ['class' => 'form-horizontal'],
	'fieldConfig' => ['inputOptions' => ['class' => 'input-xlarge']],
]);
259 260 261 262 263 264 265
... form inputs here ...
\yii\widgets\ActiveForm::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.

266 267
For more on widgets see the [View section](view.md#widgets).

268

Qiang Xue committed
269 270 271
Themes
------

ploaiza committed
272
Themes work completely different in 2.0. They are now based on a path map to "translate" a source
273
view into a themed view. For example, if the path map for a theme is
Alexander Makarov committed
274
`['/web/views' => '/web/themes/basic']`, then the themed version for a view file
275
`/web/views/site/index.php` will be `/web/themes/basic/site/index.php`.
276 277 278 279 280 281 282

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.

283 284
For more on themes see the [Theming section](theming.md).

285

Qiang Xue committed
286 287 288
Console Applications
--------------------

ploaiza committed
289
Console applications are now composed by controllers, like Web applications. In fact,
290 291 292
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
293
actions. You use the `yii <route>` command to execute a console command, where `<route>`
294 295 296 297 298 299
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()`.

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

300 301
For more on console applications see the [Console section](console.md).

302

Qiang Xue committed
303 304 305
I18N
----

306
Yii 2.0 removes date formatter and number formatter in favor of the PECL intl PHP module.
Qiang Xue committed
307

308 309
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
310
sources based on message categories. For more information, see the class documentation for [I18N](i18n.md).
311 312 313 314 315 316 317 318 319 320


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

Action filters are implemented via behaviors now. You should extend from `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 `AccessControl` filter, you should have the following
code in a controller:

321
```php
322 323
public function behaviors()
{
Alexander Makarov committed
324 325
    return [
        'access' => [
326
            'class' => 'yii\web\AccessControl',
Alexander Makarov committed
327 328
            'rules' => [
                ['allow' => true, 'actions' => ['admin'], 'roles' => ['@']],
329 330 331 332
            ),
        ),
    );
}
333
```
Alexander Makarov committed
334

335
For more on action filters see the [Controller section](controller.md#action-filters).
Qiang Xue committed
336 337 338 339 340


Assets
------

ploaiza committed
341
Yii 2.0 introduces a new concept called *asset bundle*. It is similar to script
342 343 344
packages (managed by `CClientScript`) in 1.1, but with better support.

An asset bundle is a collection of asset files (e.g. JavaScript files, CSS files, image files, etc.)
345 346 347 348
under a directory. Each asset bundle is represented as a class extending `AssetBundle`.
By registering an asset bundle via `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.
349

350
To learn more about assets see the [asset manager documentation](assets.md).
351

Qiang Xue committed
352 353 354
Static Helpers
--------------

355 356
Yii 2.0 introduces many commonly used static helper classes, such as `Html`, `ArrayHelper`,
`StringHelper`. These classes are designed to be easily extended. Note that static classes
ploaiza committed
357
are usually hard to extend because of the fixed class name references. But Yii 2.0
358 359 360
introduces the class map (via `Yii::$classMap`) to overcome this difficulty.


Qiang Xue committed
361 362 363
`ActiveForm`
------------

364
Yii 2.0 introduces the *field* concept for building a form using `ActiveForm`. A field
Qiang Xue committed
365 366
is a container consisting of a label, an input, an error message, and/or a hint text.
It is represented as an `ActiveField` object. Using fields, you can build a form more cleanly than before:
367

368
```php
369
<?php $form = yii\widgets\ActiveForm::begin(); ?>
Alexander Makarov committed
370 371
	<?= $form->field($model, 'username') ?>
	<?= $form->field($model, 'password')->passwordInput() ?>
Qiang Xue committed
372
	<div class="form-group">
Alexander Makarov committed
373
		<?= Html::submitButton('Login') ?>
374
	</div>
375
<?php yii\widgets\ActiveForm::end(); ?>
376
```
Alexander Makarov committed
377

378

Qiang Xue committed
379 380 381 382

Query Builder
-------------

383 384
In 1.1, query building is scattered among several classes, including `CDbCommand`,
`CDbCriteria`, and `CDbCommandBuilder`. Yii 2.0 uses `Query` to represent a DB query
ploaiza committed
385
and `QueryBuilder` to generate SQL statements from query objects. For example:
386

387
```php
388 389 390 391 392 393 394 395
$query = new \yii\db\Query;
$query->select('id, name')
      ->from('tbl_user')
      ->limit(10);

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

398 399 400 401

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

Qiang Xue committed
402 403 404 405

ActiveRecord
------------

406
ActiveRecord has undergone significant changes in Yii 2.0. The most important one
ploaiza committed
407
is the relational ActiveRecord query. In 1.1, you have to declare the relations
408 409 410
in the `relations()` method. In 2.0, this is done via getter methods that return
an `ActiveQuery` object. For example, the following method declares an "orders" relation:

411
```php
412 413 414 415
class Customer extends \yii\db\ActiveRecord
{
	public function getOrders()
	{
Alexander Makarov committed
416
		return $this->hasMany('Order', ['customer_id' => 'id']);
417 418
	}
}
419
```
Alexander Makarov committed
420

421 422 423 424 425 426 427 428 429 430 431 432 433

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 no longer uses the `model()` method when performing queries. Instead, you
ploaiza committed
434
use the `find()` method:
435

436
```php
437 438
// to retrieve all *active* customers and order them by their ID:
$customers = Customer::find()
Alexander Makarov committed
439
	->where(['status' => $active])
440 441 442 443
	->orderBy('id')
	->all();
// return the customer whose PK is 1
$customer = Customer::find(1);
444
```
Alexander Makarov committed
445

446 447 448 449 450 451

The `find()` method returns an instance of `ActiveQuery` which is a subclass of `Query`.
Therefore, you can use all query methods of `Query`.

Instead of returning ActiveRecord objects, you may call `ActiveQuery::asArray()` to
return results in terms of arrays. This is more efficient and is especially useful
ploaiza committed
452
when you need to return a large number of records:
453

454
```php
455
$customers = Customer::find()->asArray()->all();
456
```
457

458
By default, ActiveRecord now only saves dirty attributes. In 1.1, all attributes
ploaiza committed
459
are saved to database when you call `save()`, regardless of having changed or not,
460 461
unless you explicitly list the attributes to save.

462 463
See [active record docs](active-record.md) for more details.

464

465 466 467 468 469 470
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
ploaiza committed
471
the database driver being used:
472

473
```php
474 475
$command = $connection->createCommand('SELECT [[id]] FROM {{posts}}');
echo $command->sql;  // MySQL: SELECT `id` FROM `posts`
476
```
Alexander Makarov committed
477

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


482 483
User and IdentityInterface
--------------------------
Qiang Xue committed
484

485
The `CWebUser` class in 1.1 is now replaced by `\yii\Web\User`, and there is no more
486
`CUserIdentity` class. Instead, you should implement the `IdentityInterface` which
487 488 489
is much more straightforward to implement. The bootstrap application provides such an example.


Qiang Xue committed
490 491 492
URL Management
--------------

493 494 495 496 497
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.

498
```php
Alexander Makarov committed
499
[
500 501
	'pattern' => 'post/<page:\d+>/<tag>',
	'route' => 'post/index',
Alexander Makarov committed
502 503
	'defaults' => ['page' => 1],
]
504
```
Alexander Makarov committed
505

506
More details in the [Url manager docs](url.md).
507

Qiang Xue committed
508
Response
509 510
--------

511 512
TBD

513 514 515
Extensions
----------

516 517
TBD

518 519 520
Integration with Composer
-------------------------

521 522 523
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.
524

525
In order to learn more refer to [composer](composer.md) and [installation](installation.md) sections of the guide.