Are there any "best practices" or guidelines for using yii2 events?
Suppose I want to log AR field changes. How should I do that?
Should I use old plain afterSave() right in my model? Should I use "global" events (Event::on)? Some third option?
And where should I place the handlers? Model? Module init? some other place?
Btw, speaking of field change log: it seems like afterSave is firing after _oldAttributes are set to new values, so there’s no way to check for isAttributeChanged(). Thus another question: what handler should I use?
First off, you must find the place where you want trigger event (event is triggered by trigger() method). It is the place where you want to call any of your future callbacks. Later you will encounter situation when you will want trigger something in your place. And then you can attach event to that place via on() method.
If $yourAr is your AR then you must find out in you AR $this->trigger(‘EVENT_BEFORE_UPDATE’). Every time this code is executed your event will be executed too. If you AR is used in every controller then your internal $this->trigger(‘EVENT_BEFORE_UPDATE’) of your AR will be executed in every controller.
<?php
namespace app\controllers;
use app\models\MyModel;
class MySecondController extends Controller
{
public function actionTest()
{
$model = MyModel::find(2);
$mycallback = []; //It is your sample callback
$model->on('after_name_changing', $mycallback);
$model->changeName('some another text');
$model->save()
return 'done';
}
}
<?php
namespace app\models;
use yii\db\ActiveRecord;
class MyModel extends ActiveRecord
{
public function changName($name)
{
$this->name = $name;
$this->trigger('after_name_changing');
}
}
If you want to log changes for ALL AR classes, you should use class-level events. This should be during bootstrap process (you can create a PHP file, include it in your index.php, and put your event attaching code there).
You can attach attach both BEFORE_ and AFTER_ events. In the BEFORE_ event you save the current attributes. In AFTER_, you get the latest attributes and compare them with the one you saved to find out the changes.