Elegant usage events in Yii

Time:2021-4-20

Elegant usage events in Yii

An event used in Yii looks like this

//Binding events
$component->on($event::EVENT_NAME, [$object, 'methodNameA']);
$component->on($event::EVENT_NAME, [$object, 'methodNameB']);
//Trigger event
$component->trigger($event::EVENT_NAME, $event);

It can be seen from the above code that if you want to trigger a five listening event, you need to invade six lines of code, which is obviously not elegant enough, so you wrote a component package to bind the event and listening in the component configuration file, and only one line of code is needed to trigger the event when calling.

Source code

Environmental requirements

  • Yii > 2.0

install

$ composer require guanguans/yii-event -vvv

to configure

...
'components' => [
    ...
    'event' => [
        'class' => \Guanguans\YiiEvent\Event::className(),
        'listen' => [
            //Event class name
            \app\events\ExampleEvent::className() => [      
                //The name of the class listening to this event
                \app\listeners\ExampleListener::class,
            ],
        ],
    ],
    ...
],
...

Use examples

Create eventapp\events\ExampleEvent.php

namespace app\events;

use yii\base\Event;

class ExampleEvent extends Event
{
    public $name = 'example';
}

Create monitorapp\listeners\ExampleListener.php

namespace app\listeners;

use Guanguans\YiiEvent\ListenerInterface;
use yii\base\Event;

class ExampleListener implements ListenerInterface
{
    public static function handle(Event $event)
    {
        // to do something.
        var_export($event->name);
    }
}

Trigger event

Yii::$app->event->dispatch(new ExampleEvent());
// or
event(new ExampleEvent());

Validation results

'example'

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]