The original address is as follows: www.yiiframework.com/news/165/yi… (English version)

Translation of The Chinese content is as follows, translation participants Google translation participate in 99% abei participate in 1%, in view of the limited level, some places may be a little mouth, but the overall understanding is no problem.

We are very pleased to announce the release of version 2.0.14 of Yii Framework. Please refer to the instructions to install or upgrade to this version of http://www.yiiframework.com/download/.

This is a minor release that contains over a hundred enhancements and bug fixes, including security fixes. This is also the last version of 2.0.x to include enhancements, and we will focus on the 2.1 branch, with only bug fixes for version 2.0. We will also give a timeline for each branch when version 2.1 is released.

There are some minor changes that may affect the yii2 program you are running, so be sure to read the upgrade.md file carefully before upgrading.

Thanks to all Yii community members who contributed to this framework. We did it together!

You can follow development progress through the GitHub project of Star or Watch Yii2. There are also many active YII communities, so feel free to join if you need help or want to share your experiences.

Since yii2.1 is under development, make sure there is a version limit in your composer. Json so that it allows automatic installation of the latest version until the next major release. For version constraints that do not include 2.1, such as ~ 2.0.14, make sure there is no > = or * in the version constraints in composer.

Here’s a summary of some of the most important features/fixes included in this release.

Scalability and concurrency

While not important in the early stages of a project, scalability and concurrency issues are major obstacles to business growth.

In this release, we have identified and fixed concurrency issues that occur when writing and regenerating ids in yIwebdbSession, Also fixed an issue with using yii\ Web \DbSession, yII \ Validators \UniqueValidator and yII \ Validators \ExistValidator when master-slave.

Validator enhancement

First, ExistValidator can now check relationships when setting a new targetRelation property, which basically means that the following rule definitions can now be implemented:

public function rules(){
    return [
        [['customer_id'], 'exists', 'targetRelation' => 'customer'],
    ];
}

public function getCustomer(){
    return $this->hasOne(Customer::class, ['id' => 'customer_id']);
}Copy the code

This is a handy rule that further enhances the validation problem for relational methods, Beike said.

Another enhancement is about the FileValidator, which has a new property called minFiles that specifies the minimum number of files the user must upload, such as the code below

['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'],'maxFiles'=>6,'minFiles'=>2]Copy the code

behavior

In the behavior of convenient changes are also relatively large, you may be relatively unfamiliar with the behavior, it doesn’t matter, this topic can help you.

First, yII behaviors/BlameableBehavior adds a new $defaultValue attribute that sets the default values for properties that affect behavior when the visitor is in the state, which is often the case with the console.

Yii \ behaviors \ typecastAfterSave AttributeTypecastBehavior increase attributes, can be set to true to save the model after save typecasted. This makes the attribute types consistent when converted when saved to the database.

Added yII behaviors CacheableWidgetBehavior, which automatically caches widget contents based on specified duration and dependencies, as shown below

use yii\behaviors\CacheableWidgetBehavior;

public function behaviors(){
  return [
      [
          'class' => CacheableWidgetBehavior::className(),
          'cacheDuration' => 0,
          'cacheDependency' => [
              'class' => 'yii\caching\DbDependency',
              'sql' => 'SELECT MAX(updated_at) FROM posts',
          ],
      ],
  ];
}Copy the code

I’ll post an article on the specifics of CacheableWidgetBehavior in the dry goods section.

Databases and activity records

This release has a lot of enhancements here, let’s talk about them one at a time.

Custom data types and object conditions

Custom data type support has been implemented. Added JSON support for MySQL and PostgreSQL and array support for PostgreSQL. To do this, the query generator’s internal structure has been refactored considerably and now supports object format conditions:

$query->andWhere(new OrCondition([
    new InCondition('type', 'in', $types),
    ['like', 'name', '%good%'],
    'disabled=false',
]));Copy the code

There are two good things about it. First, it is easier to provide Yii teams with support for existing conditions and to add new ones. In addition to JSON and array conditions, it has resulted in a new BetweenColumnsCondition. More may be added in Yii 2.1. Second, it is now convenient to add custom conditions.

Query Builder Flexibility

The overall improved flexibility of the Query generator can now pass yII \db\Query anywhere supported by yII \db\Expression. For example, it can now be used as follows:

$subquery = (new Query)
    ->select([new Expression(1)])
    ->from('tree')
    ->where(['parent_id' => 1, 'id' => new Expression('tree.parent_id']));

(new Query())
    ->from('tree')
    ->where(['or', 'parent_id = 1', $subquery])Copy the code

Upserts

Another big thing is upserts for all databases supported by the Yii database layer. Upsert is an atomic operation that inserts rows into database tables if they do not exist (matching unique constraints), or updates them as they execute:

Yii::$app->db->createCommand()->upsert('pages', [
    'name' => 'Front page',
    'url' => 'http://example.com/', // URL is unique
    'visits' => 0], ['visits' => new \yii\db\Expression('visits + 1')], $params)->execute();Copy the code

A new page record is inserted atomically or its access counter is increased.

Database Migration

The generator now supports tiny integers and JSON, so you can use the following in your migration:

$this->createTable('post', [
    'id' => $this->primaryKey(),
    'text' => $this->text(),
    'title' => $this->string()->notNull(),
    'attributes' => $this->json(),
    'status' => $this->tinyInteger(),
]);Copy the code

Another migration enhancement is the ability to create and delete database views

$this->createView(
    'top_10_posts',
    (new \yii\db\Query())
        ->from('post')
        ->orderBy(['rating' => SORT_DESC])
        ->limit(10)
);

$this->dropView('top_10_posts');Copy the code

New query caching syntax

It’s convenient to use

// at query level
(new Query())->cache(7200)->all();

// at AR level
User::find()->cache(7200)->all();Copy the code

AR associated

This 👍, Active Record now resets the relevant model after the corresponding property is updated:

$item = Item::findOne(1);
echo $item->category_id; // 1
echo $item->category->name; // weapons

$item->category_id = 2;
echo $item->category->name; // toysCopy the code

Error handling

The log target will now throw an exception if the log cannot be exported correctly. It used to be ignored.

Another case is yii is now thrown yii \ web \ HeadersAlreadySentException exception, rather than before if already send the header (and therefore unable to send more information) cannot be used.

You can now configure the Yii error handler by setting the $traceLine property to generate links in the exception code so that they can be opened directly in the IDE. The configuration is similar to the debug toolbar:

'components' => [
    // ...
    'errorHandler' => [
        'errorAction' => 'site/error',
        'traceLine' => '<a href="ide://open?url={file}&line={line}">{html}</a>',
    ],
],Copy the code

Using the yii\web\ErrorAction::$layout attribute, you can easily set the layout from the ErrorAction configuration:

class SiteController extends Controller
{
    // ...
    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
                'layout' => 'error', // <-- HERE
        ],
    ];
}Copy the code

security

Two bugs were found and fixed in this release:

  • The switchIdentity() function in CVE-2018-6009 web/ user.php does not regenerate the CSRF token after changing the identity.
  • Cve-2018-6010 Remote attackers can obtain potentially sensitive information from exception messages printed by error handlers in non-debug mode.

PHP7.2

This release brings full PHP7.2 compatibility. We adjusted the yii/filters/HttpCache, FileHelper: : getExtensionsByMimeType () and yii \ web \ Session, in order to use with we support all of the PHP version.

Widgets, forms, and clients

Tags generated for script tags no longer have type attributes. Besides being better looking, it makes HTML5 tag validators happy.

When we generate form fields using ActiveForm and Html classes, we automatically match placeholders associated with the attributes of the field.

<? = Html::activeTextInput($post, 'title', ['placeholder' => true]) ? >Copy the code

One thing added to ActiveForm is the ability to select which HTML element receives the validation status class:

<? php $form = ActiveForm::begin([ 'validationStateOn' => ActiveForm::VALIDATION_STATE_ON_INPUT, ]) ? >Copy the code

The other good news is that JavaScript variables can now be registered through PHP code

class SiteController extends Controller { public function actionIndex() { $this->view->registerJsVar('username', 'SilverFire'); return $this->render('index'); }}Copy the code

Although it is a widely used method of passing data from PHP to JavaScript, consider the HTML5 data properties before using it.

The event

Paul Klimov added wildcard matches to events, and it is now possible to subscribe to multiple object or class events that match the pattern. This is useful for recording and auditing. The latest official guide has a sample of this section.

API, serialization, and filtering

When configuring JsonResponseFormatter, you can now specify the content type:

'components' => [ 'response' => [ // ... 'formatters' => [ \yii\web\Response::FORMAT_JSON => [ 'class' => \yii\web\JsonResponseFormatter::className(), 'contentType' => \yii\web\JsonResponseFormatter::CONTENT_TYPE_HAL_JSON, ], ]]]Copy the code

Data filters can now handle LT, GT, LTE and GTE on yII \ Validators \DateValidator.

Yii \ Base \ArrayableTrait::toArray() now allows recursive $fileds fields and $expand. This means that the REST API query expansion can now be specified as extra1. Extra2, and can be extended in the original data set extra1, and then extended extra2 extra1 data set, i.e. http://localhost/comments? Queries such as expand = post.author are possible.

If you need to convert model validation errors to JSON, you can now use yii\helpers JSON ::errorSummary().

Custom authentication headers are now easier to set up thanks to the addition of yii\filters\ authth \HttpHeaderAuth.

The console

How many times do you want the built-in methods to print model validation errors to the console instead of executing foreach? Now there is one:

if (! $model->validate()) { echo "Model is not valid:\n"; echo \yii\helpers\Console::errorSummary($model); return ExitCode::DATAERR; }Copy the code

The bash and ZSH commands are better done. Now it understands./ yII helps.

When calling command options can now be specified as camelCase and kebab-case, i.e. –selfUpdate and –self-update. Also, in addition to the -option = value syntax, you can now use the -option value syntax.

routing

Short dynamic syntax can now be used in URL rule groups:

'components' => [
    'urlManager' => [
        // ...
        'rules' => [
            new GroupUrlRule([
                'prefix' => 'file',
                'rules' => [
                    'POST document' => 'document/create',
                ],
            ]),
    ],
],Copy the code

i18n

The new yII \i18n\Locale component adds the getCurrencySymbol() method, which gets the currency symbol for a given Locale.

Helpers

This release brings very interesting enhancements to the Yii Assistant.

Helpers FileHelper has two new methods.

  • FindDirectories () returns directories found in the specified directory and subdirectories. It is similar to the existing findFiles(), but works with directories.
  • Unlink () removes files or symbolic links in a cross-platform manner, which has proved rather difficult to implement.

Yii helpers StringHelper gets a new matchWildcard() method, which is the same as native Fnmatch () but consistent across operating systems.

Yii \helpers\IpHelper has been added to allow IP version determination by address, comparing addresses to masks or scopes, and extending IPv6. Simple and convenient to use:

if(! IpHelper::inRange($IP, '192.168.1.0/24')) {// deny Access}Copy the code

DI Container

The dependency injection container has the ability to use definitions as attributes:

'container' => [
    'definitions' => [
        \console\models\TestService::class => [
            'class' => \console\models\TestService::class,
            'model' => Instance::of(\console\models\TestModel::class)
        ],
        \console\models\TestModel::class => [
            'class' => \console\models\TestModel::class,
            'property' => 20,
        ],
    ],
],Copy the code

In the above code, the TestService’s Model properties are set using an instance of the TestModel class configured in the dependency injection container.

summary

As the final 2.0 release of feature enhancements, this update is quite extensive, and abbe will elaborate on the highlights of v2.0.14.