Home >PHP Framework >Laravel >Do you know the implementation principle of laravel events?
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 use
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); }); }); }
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!