lumen事件使用
①bootstrap\app.php中$app->register(App\Providers\EventServiceProvider::class);取消注释
②app\Providers\EventServiceProvider.php注册事件
/** * The event listener mappings for the application. * 事件监听的映射关系 * @var array */ protected $listen = [ 'App\Events\ExampleEvent' => [ 'App\Listeners\ExampleListener', ], ]; |
③app\Events目录下定义事件
namespace App\Events; class ExampleEvent extends Event { /** * Create a new event instance. * * @return void */ public $id; public function __construct($data) { $this->id = $data['id']; } } |
④app\Listeners目录下定义事件监听者
namespace App\Listeners; use App\Events\ExampleEvent; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; class ExampleListener { /** * Create the event listener. * * @return void */ public function __construct() { // } /** * Handle the event. * * @param ExampleEvent $event * @return void */ public function handle(ExampleEvent $event) { file_put_contents('./event.txt','事件ID为'.$event->id,FILE_APPEND); } } |
⑤触发事件
$res = event(new \App\Events\ExampleEvent(array('id'=>33))); |