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

4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
There are many differences between Yii version 2.0 and 1.1, because Yii is completely rewritten for 2.0.
As a result, upgrading from version 1.1 is not as trivial as upgrading between minor versions. In this chapter,
we will summarize the major differences between the two versions.

Please note that Yii 2.0 introduces many new features which are not covered in this summary. It is highly recommended
that you read through the whole definitive guide to learn about these features. Chances could be that
some features you previously have to develop by yourself are already part of the core code now.


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

Yii 2.0 fully embraces [Composer](https://getcomposer.org/), a de facto PHP package manager. Installation
of the core framework as well as extensions are all installed through Composer. Please refer to
the [Starting from Basic App](start-basic.md) chapter 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, please refer to
the [Creating Extensions](extend-creating-extensions.md) chapter.
Qiang Xue committed
21

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
PHP
---

Yii 1.1 was developed to be compatible with PHP 5.2. Yii 2.0 minimum requirement is PHP 5.4 that is a huge improvement
in both performance and features. And since these features are actually used you need to get yourself familiar with them.
Here's the list:

- [Namespaces](http://php.net/manual/en/language.namespaces.php).
- [Anonymous functions](http://php.net/manual/en/functions.anonymous.php).
- Short array syntax. It's easy, just use `[` and `]` instead of `array(` and `)`.
- Short `echo` in form of `<?=` used in framework views. In PHP 5.4 it's always available unlike
  [`<?` that isn't safe to use](http://php.net/manual/en/language.basic-syntax.phptags.php).
- [SPL](http://php.net/manual/en/book.spl.php).
- [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).
- [intl](http://php.net/manual/en/book.intl.php). Yii 2.0 has many convenience wrappers for intl features in `i18n`
  component but it worth reading anyway to undestand it better.
Qiang Xue committed
40

Qiang Xue committed
41 42 43 44 45 46 47
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
48
You can use any core class without explicitly including that class file, thanks to the Yii
Qiang Xue committed
49 50 51
class loader.


Qiang Xue committed
52 53 54
Component and Object
--------------------

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

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


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

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

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

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

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

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

91 92
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.
93
You can override the [[yii\base\Object::init()|init()]] method to do initialization work that should be done after
94
the configuration is applied.
Qiang Xue committed
95

96 97
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
98

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

Qiang Xue committed
107
More details about configurations can be found in the [Object Configurations](basic-configs.md) chapter.
108

Qiang Xue committed
109 110 111 112 113

Events
------

There is no longer the need to define an `on`-method in order to define an event in Yii 2.0.
Qiang Xue committed
114 115
Instead, you can use whatever event names. You can trigger an event by calling
the [[yii\base\Component::trigger()|trigger()]] method:
Qiang Xue committed
116

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

Qiang Xue committed
122
And to attach a handler to an event, you can use the [[yii\base\Component::on()|on()]] method:
123 124

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

Qiang Xue committed
130
There are many enhancements to the event features. For more details, please refer to the [Events](basic-events.md) chapter.
Qiang Xue committed
131

132

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

Qiang Xue committed
136 137
Yii 2.0 expands the usage of path aliases to both file/directory paths and URLs. It also requires
an alias name to start with a `@` character so that it can be differentiated from normal file/directory paths and URLs.
138
For example, the alias `@yii` refers to the Yii installation directory. Path aliases are
Qiang Xue committed
139
supported in most places in the Yii core code. For example, [[yii\caching\FileCache::cachePath]] can take
140 141 142
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
143
alias be defined for each root namespace so that you can use Yii the class autoloader without
144 145
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
146
such as Zend Framework, you may define a path alias `@Zend` which refers to its installation
ploaiza committed
147
directory and Yii will be able to autoload any class in this library.
148

Qiang Xue committed
149
More on path aliases can be found in the [Path Aliases](basic-aliases.md) chapter.
150

151

Qiang Xue committed
152 153
Views
-----
Qiang Xue committed
154

155 156 157 158
The most significant change about views is that `$this` in a view no longer refers to
the current controller or widget. Instead, it refers to a *view* object which is a new concept
introduced in 2.0. The *view* object is of class [[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 should use `$this->context`.
Qiang Xue committed
159

160 161 162
To render a partial view within another view, you should use `$this->render()` now.
And you have to echo it explicitly because the `render()` method will return 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 172
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)
chapter for more details.
173

Qiang Xue committed
174 175 176 177

Models
------

178 179
Yii 2.0 uses [[yii\base\Model]] as the base model class which is similar to `CModel` in 1.1.
The class `CFormModel` is dropped. Instead, you should extend [[yii\base\Model]] to create a form model class.
180

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

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

195 196 197
In the above, two scenarios are declared: `backend` and `frontend`. For the `backend` scenario, both of 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.
198

199 200
The [[yii\base\Model::rules()|rules()]] method is still used to declare validation rules. Note that because
of the introduction of [[yii\base\Model::scenarios()|scenarios()]], there is no more `unsafe` validator.
201

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

206
To learn more details about models, please refer to the [Models](basic-models.md) chapter.
207

208

Qiang Xue committed
209 210 211
Controllers
-----------

212 213
Yii 2.0 uses [[yii\web\Controller]] as the base controller class which is similar to `CWebController` in 1.1.
And [[yii\base\Action]] is the base class for action classes.
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
The most obvious change when you write code in a controller action is that you should return the content
that you want to render instead of echoing it. For example,

```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;
    }
}
```

Please refer to the [Controllers](structure-controllers.md) chapter for more details about controllers.
231

232

233 234 235
Widgets
-------

236 237 238
Yii 2.0 uses [[yii\base\Widget]] as the base widget class which is similar to `CWidget` in 1.1.

To get better IDE support, Yii 2.0 introduces a new syntax for using widgets. The static methods
Qiang Xue committed
239
[[yii\base\Widget::begin()|begin()]], [[yii\base\Widget::end()|end()]] and [[yii\base\Widget::widget()|widget()]]
240
are introduced and can be used as follows,
241 242

```php
Qiang Xue committed
243 244 245
use yii\widgets\Menu;
use yii\widgets\ActiveForm;

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

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

Qiang Xue committed
258
Please refer to the [Widgets](structure-widgets.md) chapter for more details.
259

260

Qiang Xue committed
261 262 263
Themes
------

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

270
Also, there is no more `CThemeManager`. Instead, `theme` is a configurable property of the `view`
271 272
application component.

273
Please refer to the [Theming](tutorial-theming.md) chapter for more details.
274

275

Qiang Xue committed
276 277 278
Console Applications
--------------------

279 280
Console applications are now organized as controllers, like Web applications. Console controllers
should extend from [[yii\console\Controller]] which is similar to `CConsoleCommand` in 1.1.
281

282 283 284 285
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()]].
286 287 288

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

289
Please refer to the [Console Commands](tutorial-console.md) chapter for more details.
290

291

Qiang Xue committed
292 293 294
I18N
----

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

297
Message translation is now performed via the `i18n` application component.
298
The component manages a set of message sources, which allows you to use different message
299 300 301
sources based on message categories.

Please refer to the [Internationalization](tutorial-i18n.md) chapter for more details.
302 303 304 305 306


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

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

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

326
Please refer to the [Filtering](runtime-filtering.md) chapter for more details.
Qiang Xue committed
327 328 329 330 331


Assets
------

332
Yii 2.0 introduces a new concept called *asset bundle* which replaces the script package concept in 1.1.
333 334

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

340
Please refer to the [Managing Assets](output-assets.md) chapter for more details.
341

342 343 344

Helpers
-------
Qiang Xue committed
345

346
Yii 2.0 introduces many commonly used static helper classes, such as
347

348 349 350 351 352 353
* [[yii\helpers\Html]]
* [[yii\helpers\ArrayHelper]]
* [[yii\helpers\StringHelper]]
* [[yii\helpers\FileHelper]]
* [[yii\helpers\Json]]
* [[yii\helpers\Security]]
354

355 356 357

Forms
-----
Qiang Xue committed
358

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

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

374

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

378
In 1.1, query building is scattered among several classes, including `CDbCommand`,
379 380 381
`CDbCriteria`, and `CDbCommandBuilder`. Yii 2.0 represents a DB query in terms of a [[yii\db\Query|Query]] object
which can be turned into a SQL statement with the help of [[yii\db\QueryBuilder|QueryBuilder]] behind the scene.
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) chapter for more details.
Qiang Xue committed
397

398

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

402 403
Yii 2.0 introduces a lot of changes to [Active Record](db-active-record.md). Two most obvious ones are:
query building and relational query handling.
404

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

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

417 418 419
To declare a relation, you simply define a getter method that returns an [[yii\db\ActiveQuery|ActiveQuery]] object.
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()`):
420

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

431 432
You can use `$customer->orders` to access the customer's orders. You can also use the following code
to perform on-the-fly relational query with customized query conditions:
433

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

438 439 440 441
When eager loading a relation, Yii 2.0 does it differently from 1.1. In particular, in 1.1 a JOIN query
would be created to bring both the primary and the relational records; 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.
442

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

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

451 452
There are many other changes and enhancements to Active Record. Please refer to
the [Active Record](db-active-record.md) chapter for more details.
453 454


455 456
User and IdentityInterface
--------------------------
Qiang Xue committed
457

458 459 460
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.
461 462


Qiang Xue committed
463 464 465
URL Management
--------------

466 467 468 469 470
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.

471
```php
Alexander Makarov committed
472
[
473 474 475
    'pattern' => 'post/<page:\d+>/<tag>',
    'route' => 'post/index',
    'defaults' => ['page' => 1],
Alexander Makarov committed
476
]
477
```
Alexander Makarov committed
478

479
More details in the [Url manager docs](url.md).
480

481 482 483 484

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

485 486 487
If you have legacy Yii 1.1 code and you want to use it together with Yii 2.0, please refer to
the [Using Yii 1.1 and 2.0 Together](extend-using-v1-v2.md) chapter.