A use-case for global Widget events?

In Yii 2 there were events for widgets: init, beforeRun, afterRun. The only out of the box use case for these was CacheableWidgetBehavior that, when added to the class, was applying caching to the widget.

Yii 3, unlike Yii 2 doesn’t have behaviors or object-level events. Events are global and are handled via event dispatcher.

While porting widgets we’ve ported events as well but now that I thought about it, the only use case for these that comes into my mind is behaviors such as CacheableWidgetBehavior.

So the question is. Have you ever used Widget’s events globally as follows?

Event::on(Widget::class, Widget::EVENT_BEFORE_RUN, function ($event) {
    // handle it somehow
});
  • Yes. Will post my use-case.
  • No. But will post possible use-case.
  • No.

0 voters

1 Like

It may help with timings collection when you want to understand how much time does each widget take. But I don’t think it’s the use case for events implementing.

1 Like

They are not necessarily used in the Widget but if in other classes, sometimes it is better to have them and not use them, than to need them and not have them, here a case in a controller.

    Event::on(RegistrationController::class, FormEvent::REGISTER_FAILS, function ($e) {
        \Yii::$app->session->setFlash(
            'warning',
            \Yii::t(
                'app.user',
                'The account could not be created. Contact the administrator.'
            )
        );
    });

    /**
     * RegistrationController/FormEvent::REGISTER_MODULE_DISABLE
     */
    Event::on(RegistrationController::class, FormEvent::REGISTER_MODULE_DISABLE, function () {
        \Yii::$app->session->setFlash(
            'danger',
            \Yii::t('app.user', 'Module register user is disabled in the application configuration.')
        );
    });

Your example is not about one of init, beforeRun, afterRun. That’s custom event. Nothing prevents you from triggering it in your widget via event dispatcher you require in your widget constructor.

2 Likes

Events were removed.