📜 ⬆️ ⬇️

Yii2 bad behaviors

The minimum PHP version for Yii2 is 5.4. The minimum PHP version for Traits is 5.4. Coincidence? I do not think!



Yii2 has long been time to get rid of these bad behaviors. And that's why.

Take as an example the implementation of the SoftDelete behavior for ActiveRecord using PHP Traits. And consider the points that it gives us.
')
Greater control over the model
Obviously, by marking the records as “deleted”, you expect that they will not pull into the results of any of your queries: Cat :: find () -> all () , Cat :: find () -> one () , etc. Yii1 allowed to implement such functionality in the CActiveRecord :: beforeFind () event. However, after a thorough revision of ActiveRecord in Yii2, for obvious reasons, such an event no longer exists, and the task goes into the category of unsolvable, because behaviors can only work with AR events. On the contrary, when using traits you are free to override any method of the model, for example, like this:
public static function find() { $query = parent::find(); // Skip deleted items if (static::$softDelete) { $query->andWhere([static::tableName() . '.' . static::$softDeleteAttribute => null]); } return $query; } 


Full IDE support
Yes, using behaviors you can add new attributes to the model, but the IDE will not know anything about it, and we are not even talking about any autocomplex. But when using traits, IDE perfectly catches all new methods and properties, including virtual ones:
  * @property-read bool $isDeleted */ trait SoftDelete 

And now the isDeleted property will be highlighted in all AR objects to which the trait SoftDelete is connected:
 class Cat extends ActiveRecord { use \common\traits\SoftDelete; } $cat = (new Cat)->isDeleted; // Property "isDeleted" autocompleted by IDE 


Minus one bike
With the advent of traits, behaviors actually became a bicycle. And a conscientious developer risks to suffer a lot, having spent a lot of time studying this traits substitute, and trying to solve the above problems. It was a really good decision in Yii1, but now it’s an overhead head on level ground when learning and using the framework. It's time to say goodbye to them.

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


All Articles