Trong bản cập nhật Laravel 5.8.9 này thì có một tính năng mới được thêm vào đó là Automatic Event/Listener Discovery
Mục đích
Không còn cần thiết phải đăng ký thủ công các sự kiện (events) và trình lắng nghe (listeners) trong EventServiceProvider
.
Cách kích hoạt
Trong file app/Providers/EventServiceProvider.php
thêm function sau để kích hoạt
**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return true;
}
Cách hoạt động
Nó sẽ tự động dò tìm các file listener trong thư mục app/Listeners, mỗi khi có sự kiện gì phát sinh, toàn bộ các Listeners này sẽ lắng nghe và giải quyết. Các method public handle hoặc bắt đầu bằng handle sẽ được thực thi.
Mặc định thư mục app/Listeners, nếu muốn đăng ký thêm thư mục khác thì thêm fuction này vào app/Providers/EventServiceProvider.php
**
* Get the listener directories that should be used to discover events.
*
* @return array
*/
protected function discoverEventsWithin()
{
return [
$this->app->path('Listeners'),
$this->app->path('OtherListeners'),
// ...
];
}
Làm thế nào Listeners bắt đùng Event?
Tạo một file Listener: php artisan make:listener NVKSoltuionBlogListener
<?php
namespace App\Listeners;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class NVKSolutionBlogListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
// code
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handle(DefaultEvent $event)
{
//
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handleEvent1(Event1 $event)
{
// code
}
/**
* Handle the event.
*
* @param object $event
* @return void
*/
public function handleEvent2(Event2 $event)
{
// code
}
}
Command cho Event/Listener Discovery
Show list events
Cache
Chạy lệnh này trên môi trường Production nha
php artisan event:cache