User Events

The following is the list of the user events and where they happen:

On Controllers

On Models

How to Work With User Events

All these events receive an instance of Da\User\Event\UserEvent. The Event receives an instance of a Da\Model\User class that you could use for whatever logic you wish to implement.

The recommended way to make use of events is by creating a new file in your config folder (i.e. events.php), configure there all your events and then include that file on your entry script.

Here is an example of setting an event for the AdminController and the User model:

// events.php file

use Da\User\Controller\AdminController;
use Da\User\Event\UserEvent;
use Da\User\Model\User;
use yii\base\Event;

// This will happen at the controller's level
Event::on(AdminController::class, UserEvent::EVENT_BEFORE_CREATE, function (UserEvent $event) {
    $user = $event->getUser();

    // ... your logic here

// This will happen at the model's level
Event::on(User::class, UserEvent::EVENT_BEFORE_CREATE, function (UserEvent $event) {

    $user = $event->getUser();

    // ... your logic here

Now, the only thing I need to do is adding the events.php file to your entry script (i.e. index.php). The following is taken from the Yii 2 Advanced Application Template:

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
require(__DIR__ . '/../../common/config/bootstrap.php');
require(__DIR__ . '/../config/bootstrap.php');

require(__DIR__ . '/../config/events.php'); // <--- adding events here! :)

$config = yii\helpers\ArrayHelper::merge(
    require(__DIR__ . '/../../common/config/main.php'),
    require(__DIR__ . '/../../common/config/main-local.php'),
    require(__DIR__ . '/../config/main.php'),
    require(__DIR__ . '/../config/main-local.php')

$application = new yii\web\Application($config);

© 2amigos 2013-2019