📜 ⬆️ ⬇️

Yii 2.0 RC

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

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

Frequently asked Questions


')




Major improvements in 2.0 RC



This release has a lot 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 learn the framework in general, read the full manual .

Security


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

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

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

Work with database


Replication and read / write sharing


Read-write splitting replication and partitioning are now supported by the framework kernel. During replication, data is replicated from the master servers to the slave server . All recording and updates should be done on the master servers, and reading can be made 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.

Transactions


There have been several improvements on transactions.

First, you can work with callback-style transactions:

 $connection->transaction(function() { $order = new Order($customer); $order->save(); $order->addItems($items); }); 


Which is equivalent to a longer code:

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


Secondly, transactions cause several events. For example, the beginTransaction event is beginTransaction by a database connection when a new transaction starts, and commitTransaction is called if the commitTransaction is successful. You can use these events for various pre- and post-processing.

Finally, you can specify the isolation level of a transaction (for example, READ COMMITTED ) when it starts:

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


Build query


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

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


When building in or not you can use subqueries:

 $subquery = (new \yii\db\Query) ->select('id') ->from('user') ->where(['>=', 'age', 30]); //  ,     30  $orders = (new \yii\db\Query) ->from('order') ->where(['in', 'customer_id', $subquery]) ->all(); 


Resource management


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

Because of this change, you need to install a 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 vendor directory:

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


Read more about the resources in the full manual .

Data formatting


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

We also standardized the date and time formats. Now mainly ICU format is used . Classes such as DateValidator and JUI DatePicker use this default format. PHP formats can be used through the php: 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) 


Forms


Improvements touched JavaScript component ActiveForm .

Instead of using callbacks during the validation process, events are now triggered. Using them is quite 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 deferreds parameter for the beforeValidate event allows you to add a new Deferred object. FileValidator and ImageValidator now support validation on the client due to deferred validation.

Some methods in ActiveForm JavaScript code ActiveForm become part of the API, which makes it easier to create dynamic forms with support for validating added fields on the client side. For example, the following JavaScript code can be used to validate the newly 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 logging goals included by default in the framework automatically convert them to textual representation. In its class log target, you can handle such data in a special way.

InvalidCallException , InvalidParamException , UnknownMethodException now inherited from BadMethodCallException from SPL, which makes the hierarchy of exceptions more logical.

When exceptions are displayed, the arguments of the methods are now displayed in the framerays.

Developer Tools


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

The Gii code generator can now be used from the console. Previously, only the web interface was provided, which, although very intuitive, does not appeal to hardcore console gamers. Now everyone should be satisfied. 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 


Behavior


We have added the new yii\behaviors\SluggableBehavior , which allows you to fill in a specific attribute of the transliterated model with a ready-to-use version of the URL in the URL. You can use it 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:

 $component->attachBehaviors([ '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 features of Yii, which, judging by the reviews, makes it possible to work with Smarty and Twig as effectively as with regular PHP templates. Learn more about the new syntax in the full manual .

Documentation in Russian


The documentation is partially translated into Russian, but the translation is not final and can be read either directly from GitHub or by generating the HTML yourself . Thank you so much
Russian-speaking community for direct participation in the translation.

Source: https://habr.com/ru/post/238447/


All Articles