lumen 事件
今天需要实现日志功能,所有使用了一下lumen的event(事件)和listener(监听)
Lumen事件:https://lumen.laravel-china.org/docs/5.3/events http://laravelacademy.org/post/3441.html
Laravel 的事件系统:https://d.laravel-china.org/docs/5.5/events
Laravel 5 事件的使用:https://www.cnblogs.com/chenqionghe/p/4884390.html
看完上面的文章基本就能实现了,下面做一些记录
我需要实现开门的日志写入
首先是OpenDoorEvent.php
<?php namespace App\Events; class OpenDoorEvent extends Event { /** * Create a new event instance. * * @return void */ public $data; public function __construct($data) { $data['ip'] = $_SERVER["REMOTE_ADDR"]; $data['open_time'] = date('Y-m-d H:i:s', time()); $this->data = $data; } public function getData() { return $this->data; } }
然后实现OpenDoorListener.php
<?php namespace App\Listeners; use App\Events\OpenDoorEvent; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; class OpenDoorListener { public $data; /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param ExampleEvent $event * @return void */ public function handle(OpenDoorEvent $event) { $data = $event->getData(); $this->data = $data; $this->run(); } public function run() { if (!$this->data) return; var_dump($this->data); /** ... */ } }
接下来是注册监听EventServiceProvider.php
<?php
namespace App\Providers;
use App\Events\OpenDoorEvent;
use App\Listeners\OpenDoorListener;
use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* @var array
*/
protected $listen = [
'App\Events\SomeEvent' => [
'App\Listeners\EventListener',
],
/*
'App\Events\OpenDoorEvent' => [
'App\Listeners\OpenDoorListener',
],
*/
OpenDoorEvent::class => [
OpenDoorListener::class
],
];
}
最后随便找个控制器调用一下,在run方法把$data输出
$data = [ 'user_id' => 1, 'room_id' => 1, 'key' => '123456', 'status' => 1 ]; event(new OpenDoorEvent($data));exit();
结果
array(6) { ["user_id"]=> int(1) ["room_id"]=> int(1) ["key"]=> string(6) "123456" ["status"]=> int(1) ["ip"]=> string(9) "127.0.0.1" ["open_time"]=> string(19) "2018-01-30 15:46:24" }
有问题欢迎留言!