Laravel 事件系统新特性
事件发现
Tips:版本大于 5.8.9 才有这个特性
查看事件服务提供者父类 Illuminate\Foundation\Support\Providers\EventServiceProvider.php
<?php
namespace Illuminate\Foundation\Support\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Events\DiscoverEvents;
class EventServiceProvider extends ServiceProvider
{
...
...
/**
* 判断是否要自动发现事件和侦听器(默认关闭)。
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
/**
* 获取发现事件的侦听器目录
*
* @return array
*/
protected function discoverEventsWithin()
{
return [
$this->app->path('Listeners'),
];
}
}
进入 app/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
...
...
...
public function shouldDiscoverEvents()
{
return true;
}
}
如此操作后,就不用在 $listen 数组中,手动注册事件与侦听器。
Tips:在生产环境中,我们肯定不希望每次请求时都扫描所有侦听器。因此,在部署过程中,我们可以运行 event:cache 命令来缓存应用程序所有事件和侦听器的对应关系。来加快事件注册。event:clear 命令可用于销毁缓存。
- event:cache 发现并且缓存应用中的事件和侦听器
- event:clear 清除被缓存的事件和侦听器
- event::list 可列出应用中所有事件和侦听器
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: