Home >PHP Framework >Laravel >Do you know the implementation principle of laravel events?

Do you know the implementation principle of laravel events?

藏色散人
藏色散人forward
2020-06-22 13:55:193792browse

The following tutorial column will introduce you to the implementation principles of laravel events. I hope it will be helpful to friends in need!

Simple useDo you know the implementation principle of laravel events?

1. Configure the listen attribute of the event and listener App\Providers\EventServiceProvider
protected $listen = [
        'App\Events\UserAdd' => [
            'App\Listeners\UserAddListener',
        ],
    ];
2. Generate the corresponding event class and listening class files.

php artisan event:generate

will generate two class files: App\Events\UserAdd and App\Listeners\UserAddListener.

The event class is mainly used to save the corresponding information. For example, an attribute saves the user model instance, and the event class instance will be passed to the handle method of the corresponding event listener to process the event logic.

public function __construct(User $user)
{
   $this->user = $user;//创建事件实例时保存的信息
}

App\Listeners\UserAddListener The handle method of the listener is where the logic is processed

public function handle(UserAdd $event)
{
        dd($event->user);//获取到对应事件实例的信息
}

3. To trigger events, use the public function events(). Pass in the instance of the corresponding event class

event(new \App\Events\UserAdd($user));//执行这一步时,就会执行到handle方法

Implementation principle (Illuminate\Events\Dispatcher class)

public function register()
{
    $this->app->singleton('events', function ($app) {
        return (new Dispatcher($app))->setQueueResolver(function () use ($app) {
            return $app->make(QueueFactoryContract::class);
        });
    });
}

The events registered to the IOC container are actually Illuminate\Events\Dispatcher The class, that is, the facade Event actually calls the method of this classImportant attributes and methods:

protected $listeners = [];
protected $wildcards = [];
protected $wildcardsCache = [];//这三个属性都是配置事件与监听器关系的数组,时间注册进来后就是放到对应的数组里面的。
//这个方法就是注册事件用的,把配置好的事件注入到上面的属性中
public function listen($events, $listener)
    {
        foreach ((array) $events as $event) {
            if (Str::contains($event, '*')) {
                $this->setupWildcardListen($event, $listener);
            } else {
                $this->listeners[$event][] = $this->makeListener($listener);
            }
        }
    }
//这个方法就是执行对应事件监听器的方法,找到事件下面的是所有监听器,然后执行。
public function dispatch($event, $payload = [], $halt = false),

The above is the detailed content of Do you know the implementation principle of laravel events?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete