Yii 2.0 RC

    We are very pleased to announce the release of RC (candidate release) PHP-framework Yii 2.0. To install the framework or upgrade, follow the instructions at yiiframework.com .

    In this version, about a hundred errors have been fixed, more than two hundred improvements have been made, and there are new features. It is the result of five months of intensive development, counted from beta . During this time, the framework community actively helped us. Thanks to everyone who helped Yii and without whom this release would not have taken place. You are best!


    • What does 2.0 RC mean? RC means Release Candidate, that is, the last release before stable GA (General Availability). He was left, mainly, edits of minor problems and documentation.
    • When will the stable release be? It all depends on what problems will be with RC. The preliminary plan is to make a stable release in about two weeks. Of course, if the RC proves to be quite stable.
    • Can I use RC in my projects? Yes. We strongly recommend trying it on new projects and we would be grateful for error messages and just feedback. Since a stable release will be soon, we do not recommend using RC on combat servers because, although this is unlikely, backward compatibility may still be broken in the stable version.
    • Is there any 2.0 documentation? Yes, a complete guide , which is the most comprehensive 2.0 documentation and API documentation, is a reference guide that will help you use specific framework classes.
    • How to upgrade from 1.1 to 2.0? Read Upgrading from Yii 1.1 . Just note that 2.0 is completely rewritten and the update is not trivial. If your 1.1 application works well and stably, we recommend that you continue to use 1.1, unless of course you have additional time and resources to upgrade.
    • How to upgrade from beta or alpha 2.0? Read the instructions in UPGRADE .
    • How to follow development 2.0? All development takes place on GitHub: github.com/yiisoft/yii2 . To receive information about changes, you can mark the project with an asterisk. You can also subscribe to our twitter twitter.com/yiiframework and join the Facebook group .

    Major improvements in 2.0 RC

    This release has a large number of useful changes and improvements. Below we describe the most important. A complete list of changes can be found in CHANGELOG . If you want to know the framework in general, read the complete manual .


    Several security experts, including Tom Worster and Anthony Ferrara , have helped us with checking the framework code and have provided many comments and suggestions. Tom helped rewrite part of the code, which allowed to improve key generation, use stronger encryption, protect against timing attack and many other types of attacks.

    For more convenient configuration, the helper has Securitybecome a component of the application security. As a result, you can access it as Yii::$app->security->encrypt().

    In addition, a number of small but important safety changes have been made. For example, it httpOnlyis now enabled for all cookies by default, and CSRF tokens can be stored in sessions instead of cookies if set yii\web\Request::enableCsrfCookiein false.

    Work with the database

    Replication and read / write sharing

    Read-write splitting and replication are now supported by the core framework. During replication, data is replicated from master servers to server slaves . All recording and updates should be done on the master servers, and reading can be done from slave servers. To use this feature, configure the database connection as follows:

        'class' => 'yii\db\Connection',
        // конфигурация для master
        'dsn' => 'dsn for master server',
        'username' => 'master',
        'password' => '',
        // общая конфигурация для slave-ов
        'slaveConfig' => [
            'username' => 'slave',
            'password' => '',
        // список конфигураций slave-ов
        'slaves' => [
            ['dsn' => 'dsn для slave 1'],
            ['dsn' => 'dsn для slave 2'],
            ['dsn' => 'dsn для slave 3'],

    With this configuration, you can continue to write code as before. If the request selects data, one of the slaves will be automatically used (a simple load balancing algorithm is used to select the server). If the query updates or inserts data, master will be used.


    Several enhancements have been made to the topic of transactions.

    First, you can work with transactions in the style of callbacks:

    $connection->transaction(function() {
        $order = new Order($customer);

    Which is equivalent to a longer code:

    $transaction = $connection->beginTransaction();
    try {
        $order = new Order($customer);
    } catch (\Exception $e) {
        throw $e;

    Secondly, transactions trigger several events. For example, an event beginTransactionis triggered by a connection to the database when a new transaction starts, and commitTransactionis raised when a successful commit is made. You can use these events for various pre- and post-processing.

    Finally, you can specify the transaction isolation level (for example, READ COMMITTED) at its start:

    $transaction = $connection->beginTransaction(Transaction::READ_COMMITTED);

    Query building

    When building a query, you can now use any operators. In the example below age >= 30, a statement is used for a condition >=. Yii properly escapes the field name, and uses a parameter binding for the value.

    $query = new \yii\db\Query;
    $query->where(['>=', 'age', 30]);

    When building inor notyou can use subqueries:

    $subquery = (new \yii\db\Query)
        ->where(['>=', 'age', 30]);
    // выбираем заказы, которые сделали клиенты старше 30 лет
    $orders = (new \yii\db\Query)
        ->where(['in', 'customer_id', $subquery])

    Resource management

    Yii uses the Bower and NPM packages , i.e. jQuery, jQuery UI, Bootstrap, through Composer using the wonderful Composer Asset Plugin .

    Because of this change, you must install the plugin once before using Yii:

    php composer.phar global require "fxp/composer-asset-plugin:1.0.0-beta2"

    Now, using the following command, you can install the Bower jQuery package in the directory vendor:

    php composer.phar require bower-asset/jquery:2.1.*

    Read more about resources in the complete guide .

    Data formatting

    We have significantly refactored the data yii\base\Formatterand formatter yii\i18n\Formatter. Now there is only one class yii\i18n\Formatter. The new formatter provides a single interface regardless of the presence of the intl extension on the PHP server. If the extension is not installed, formatting will be done using the framework and will not support internationalization.

    We also standardized date and time formats. Now mainly the ICU format is used . Classes like DateValidatorJUI DatePickeruse this format by default. PHP formats can be used through a prefix php:.

    $formatter = Yii::$app->formatter;
    $value = time();
    echo $formatter->asDate($value, 'MM/dd/yyyy'); // эквивалентно date('m/d/Y', $value)
    echo $formatter->asDate($value, 'php:Y/m/d');  // эквивалентно date('Y/m/d', $value)
    echo $formatter->asDate($value, 'long');       // эквивалентно date('F j, Y', $value)


    Improvements have also been made to the JavaScript component ActiveForm.

    Instead of using callbacks, validation events are now fired. Using them is pretty simple:

    $('#myform').on('beforeValidate', function (event, messages, deferreds) {
        // Вызывается до валидации всей формы сразу после нажатия submit.
        // Тут можно провести дополнительные проверки.
    $('#myform').on('beforeSubmit', function () {
        // Вызывается после удачной валидации всех полей и до того как форма отправляется на северер.
        // Тут можно отправить форму через AJAX. Не забудьте вернуть false для того, чтобы форма не отправлялась как обычно.

    Deferred validation is also supported. In the example above, the parameter deferredsfor the event beforeValidateallows you to add a new Deferred object. FileValidatorand ImageValidatornow they support validation on the client thanks to deferred validation.

    Some methods in JavaScript code ActiveFormhave become part of the API, which makes it easier to create dynamic forms with support for validation of added fields on the client side. For example, the following JavaScript code can be used to validate the just added “address” field:

    $('#myform').yiiActiveForm('add', {
        'id': 'address',
        'name': 'address',
        'container': '.field-address',
        'input': '#address',
        'error': '.field-address .help-block'

    Logging and error handling

    You can use arrays and objects as data when logging. All log targets included by default in the framework automatically convert them to textual representation. In its class, the goal of the log can process such data in a special way.

    InvalidCallException, InvalidParamException, UnknownMethodExceptionIs now inherited from the BadMethodCallExceptionfrom the SPL, which makes exceptions more logical hierarchy.

    When displaying exceptions, method arguments are now shown in the stack trace.

    Developer Tools

    The Yii debugger is a very useful tool that displays detailed information about the progress of an application. We added a new panel to it that shows the loaded resource bundles and their contents.

    The Gii code generator can now be used from the console. Previously, only a web interface was provided, which, although very intuitive, is not liked by hardcore consoles. Now everyone should be happy. Moreover, the generator code has not changed. When creating your own generator, you don’t have to do double work: both the console and the web use the same code.

    To try Gii in the console, run the following commands:

    # перейдите в базовую директорию приложения
    cd path/to/AppBasePath
    # смотрим справку по Gii
    yii help gii
    # смотрим справку по генератору моделей
    yii help gii/model
    # генерируем модель City на основе таблицы city
    yii gii/model --tableName=city --modelClass=City


    We have added a new behavior yii\behaviors\SluggableBehaviorthat allows you to populate a specific attribute of the model with a transliterated version of the string that is ready to use in the URL. It can be used as follows:

    use yii\behaviors\SluggableBehavior;
    public function behaviors()
       return [
               'class' => SluggableBehavior::className(),
               'attribute' => 'title',
               // 'slugAttribute' => 'alias',   // храним строку для URL (или slug) в поле "alias"
               // 'ensureUnique' => true,       // нам нужны только уникальные slug-и

    Behaviors can now join anonymously:

        'myBehavior1' => new MyBehavior,  // именованное поведение
        MyBehavior::className(),          // анонимное поведение

    Template engines

    The Smarty and Twig extensions have been significantly improved. For each of them, a special syntax was introduced for many of the features of Yii, which, judging by the reviews, allows you to work with Smarty and Twig as effectively as with regular PHP templates. For more information on the new syntax, see the complete guide .

    Documentation in Russian

    The documentation is partially translated into Russian, but the translation option is not final and you can read it either directly from GitHub , or by generating HTML yourself . Many thanks to the
    Russian-speaking community for their direct participation in the translation.

    Also popular now: