Home>Article>PHP Framework> About Laravel events & asynchronous processing
The following is an introduction to Laravel events & asynchronous processing from theLaravelframework tutorial column. I hope it will be helpful to friends in need!
php aritsan make:event Test
Events and monitoring listen is one-to-many management. One event corresponds to multiple response events.
Define a$data
attribute and assign the data passed when the event is triggered.
public $data; /** * Create a new event instance. * * @return void */ public function __construct($data) { $this->data = $data; }
public function test(){ Test::dispatch('你好事件'); }
php artisan make:listener TestLisenter
namespace App\Lisenter;use App\Events\Test;class TestLisenter { public function handle(Test $test) { var_dump($test->data); //打印:你好事件 }}
At this time we need to create a listen object to handle the business logic
laravel provides two solutions:
Add $listen array information inEventServiceProvider
For example:
/** * 应用程序的事件监听器映射 * * @var array */protected $listen = [ 'App\Events\Test' => [ 'App\Listeners\TestListenter', ],];
Let the system automatically process and traverse The specified directory
needs to be added inEventServiceProvider
:
/** * 确定是否应自动发现事件和侦听器 * * @return bool */public function shouldDiscoverEvents(){ return true;}
/** * 获取应该用于发现事件的监听器的目录 * * @return array */ protected function discoverEventsWithin() { return [ $this->app->path('Lisenter'),//事件关联的监听器目录APP/Lisenters $this->app->path('Lisenter/test'),//事件关联的监听器目录APP/Lisenters/test ]; }
The system will automatically match Listen
At this time, the event process has been completed. If it is not successful or you want to know more about event processing, such as delay queue, judging whether to join the event, processing after failure, etc.: refer to the document
If you have no contact with Laravel's queue, please refer to: Laravel Jobs
You only need to implement the ShouldQueue interface in TestListenter
It looks like this:
namespace App\Lisenter;use App\Events\Test;use Illuminate\Contracts\Queue\ShouldQueue;class TestLisenter implements ShouldQueue{ public function handle(Test $test) { var_dump($test->data); //打印:你好事件 }}
The above is the detailed content of About Laravel events & asynchronous processing. For more information, please follow other related articles on the PHP Chinese website!