Laravel 事件提供了简单的观察者模式实现,允许你订阅和监听应用中的事件。
事件和监听都是阻塞式应用,如果耗时的监听和事件,请使用队列操作。
版本
laravel5.2
注册事件/监听器
文件app\Providers\EventServerProvdier.php
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
'App\Events\CacheEvent' => [
'App\Listeners\CacheEventListener',
],
执行生成命令
php artisan event:generate
事件将在app\Events生成
CacheEvent.php
SomeEvent.php
监听器将在app\Listeners生成
SomeEventListener.php
CacheEventListener.php
比如现在有个例子,我需要将读取的数据缓存,这个场景只是举例,实际用途按自己来
CacheEvent 事件写依赖注入
<?php
namespace App\Events;
use App\Model\Post;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class CacheEvent extends Event
{
use SerializesModels;
public $post;
/**
* Create a new event instance.
将Post实例依赖注入
*
* @return void
*/
public function __construct(Post $post)
{
//
$this->post = $post;
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
CacheEventListener监听
<?php
namespace App\Listeners;
use Cache;
use Log;
use App\Events\CacheEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class CacheEventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param CacheEvent $event
* @return void
*/
public function handle(CacheEvent $event)
{
//这里已经把事件的依赖取得。这里是阻塞的
$post = $event->post;
$key = 'post_'.$post->id;
Cache::put($key,$post,60*24*7);
Log::info('保存文章到缓存成功!',['id'=>$post->id,'title'=>$post->title]);
}
}
控制器调用监听事件
引入事件的命名空间和事件调用的命名空间
use App\Events\CacheEvent;
use Event;
public function index(Request $request){
$post=Post::find(1);
print_r($post->toArray());
Event::fire(new CacheEvent($post));
//或使用函数,event(new CacheEvent($post));
return view('index');
}
事件监听器队列
只需要加入一个继承接口,通过php artisan event:generate生成已经加入了命名空间。
class CacheEventListener implements ShouldQueue
{
...
}
测试发现,这个监听队列,不是我们说的队列,他是阻塞式,带后续研究再补充。
手动注册事件
在文件app\Providers\EventServerProvdier.php的handle方法中假设定义如下
public function boot(DispatcherContract $events)
{
parent::boot($events);
$events->listen('event.hello', function ($param1,$param2) {
echo $param1,$param2;
});
//
}
控制器调用
public function index(Request $request){
$post=Post::find(1);
// print_r($post->toArray());
Event::fire('event.hello',['hello,','world!']);//参数使用数组
return view('index');
}
输出
hello,world!
网友评论