Upgrading from PHP Yii 1.x to Yii2

Upgrading from PHP Yii 1.x to Yii2
COMMENTS ()
Tweet

Hey Guys!
In this post I’m going to show you how to upgrade your PHP Yii application from Yii 1.x to Yii2. As you know, there’s no way to upgrade from Yii1 to Yii2 without re-writing code, since the Yii framework has been completely rewritten from the ground up for Yii 2.0. So you can’t just upgrade your application directly on the new version. Therefore, depending on the nature and complexity of your web app, you may need to modify the code in order to upgrade to Yii2. We’ll look at these efforts in detail in this post.

PHP Requirements

Let’s start with the PHP requirements which you’ll need in order to upgrade your web app to Yii2. Yii 2.0 requires PHP 5.4 or above, so if your current application is below PHP 5.4, you’ll need to upgrade your PHP version first. Below is a summary of the major changes in PHP that this involves.

  • Namespaces
  • Anonymous functions
  • Short array syntax […elements…] is used
  • Short echo tags
  • SPL classes and interfaces
  • Late Static Bindings
  • Date and Time
  • Traits
  • Intl extension

Namespace

For starters, the “C” prefix is no longer used in class names. So, you’ll need to change most of the class names in your web app that use the “C” prefix. Since almost every core class is namespaced, (e.g., yii\web\Request), you’ll need to include the core classes using namespaces.

Events

If you’ve used events like onBeforeSave, etc. you’ll will need to change the event calls. In Yii 2.0 you can now use any event name. So you can trigger an event by calling the trigger() method (as shown below)

$event = new \yii\base\Event;
$component->trigger($eventName, $event);

 

 

To attach a handler to an event, use the on() method (depicted below).

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

 

There are many similar enhancements to Event features. For more details on those, please refer to the Events section in the Yii 2.0 guide.

Path Aliases

Yii2 requires an alias name to start with the @ character, to differentiate aliases from normal file/directory paths or URLs as the usage of path aliases is expanded to both file/directory paths and URLs. If you’ve used path aliases you may need to add @ character to instances where required.
More on path aliases can be found in the Aliases section of Yii2 guide.

Views

In Yii2 the $this function in a view no longer refers to the current controller or widget. Instead, it refers to the yii\web\View object. So if you want to access the controller or widget in a view, you should use $this->context. You’ll need to make this change in your web app’s code depending how many places you’ve used $this in your views.
Also, there is no $this->renderPartial() function in Yii2. So you’ll need to change all occurrences of renderPartial() in your app if you’ve used it. In Yii2, you need to echo what is returned by the $this->render() function to get this the same result. For example:

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

 

Controllers

You’ll also need to alter most of the controller actions in your web app, so that the action returns the content that you want to render instead of echoing it (as shown below).

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 section of the Yii2 guide for more details.

Naming Actions

Another important change in Yii2 is in the naming convention for routes. In Yii 2.0 camel case names of controllers and actions are now converted to lower case where each word is separated by a hyphen. For e.g. the controller id for the CamelCaseController will be camel-case. For more info on changes in naming conventions, please see the section about controller IDs and action IDs in the Yii2 guide.

Widgets

In Yii2 the CWidget has been replaced by the yii\base\Widget. So you’ll need to change the code in places where you’ve used this widget. In Yii 2.0, static methods like begin(), end(), and widget() have also been introduced and are used in the following manner:

use yii\widgets\Menu;
use yii\widgets\ActiveForm;

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

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

 

Please refer to the Widgets section of the Yii2 guide for more details on these changes.

Themes

Themes are also completely differently in Yii 2.0, as they are now based on a path mapping mechanism that maps a source view file path to a themed view file path. For example, if the path map for a theme is [‘/web/views’=>’/web/themes/basic’], then the themed version for the view file /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 a view rendered outside of the context of a controller or a widget. Furthermore, the CThemeManager component has also been removed in Yii2. Instead, the theme is a configurable property of the view application component.
Please refer to the Theming section of the Yii2 guide for more details on these changes.

Console Applications

In Yii 2.0 the CConsoleCommand has been replaced with the yii\console\Controller class, since console applications are now organized as controllers. Therefore all console controllers should extend from yii\console\Controller class. And the controller route (e.g. sitemap/index) is used to run a console command. If you’ve used console commands in your web application, you will need to make these changes before you can upgrade to Yii2.
Please refer to the Console Commands section of the Yii2 guide for more details about these changes.

I18N

Similarly, if you’ve used Yii’s built-in date/number formatters in your web app, you need to change those as well, since they will not work in Yii 2.0, as Yii2 uses the PECL intl PHP module now.
Please refer to the Internationalization section of the Yii2 guide for more details on these changes.

Query Builder

For query builder, the CDbCommand, CDbCriteria and CDbCommandBuilder functions won’t work in Yii 2.0 either. You’ll need to replace these with the yii\db\Query object, that can be turned into an SQL statement with the help of yii\db\QueryBuilder behind the scenes. For example:

$query = new \yii\db\Query();
$query->select('id, name')
      ->from('user')
      ->limit(10);

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

Please refer to the Query Builder section of the Yii2 guide for more details about these changes.

 

Summary

Keeping in mind all these changes, a lot of effort may be required to upgrade your web app from Yii1.x to Yii 2.0, depending on how many of the above features you’ve used in your app. If it’s a smaller application or one that is still in the initial phases of development, then you probably won’t have to make that many changes. But it’s a large or complex application, you’ll have your work cut out for you.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812