laravel5事件与监听使用教程例子:
1、注册事件-监听器
首先我们需要在EventServiceProvider中注册事件与监听器之间的映射关系:
protected $listen = [
'App\Events\自定义Event' => [
'App\Listeners\自定义Listener',
],
];
然后我们在项目根目录运行如下Artisan命令:
php artisan event:generate
该命令会在 app/Events 目录下生成 自定义Event.php ,在 app/Listeners 目录下生成 自定义Listener.php 。
2、定义事件类
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class UserLoginEvent extends Event
{
use SerializesModels;
public $自定义;//定义公共变量
/**
* Create a new event instance.
*
* @return void
*/
public function __construct($自定义)
{
$this->当前事件的类的方法=$自定义;
//当前事件的类的方法/如一个控制器的方法
}
/**
* Get the channels the event should be broadcast on.
*
* @return array
*/
public function broadcastOn()
{
return [];
}
}
3定义监听器
<?php
namespace App\Listeners;
use Log;
use App\Events\UserLoginEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
//这里你如果调用其它的就要 use 进来
class UserLogintListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param UserLoginEvent $event
* @return void
*/
public function handle(自定义Event $event)
{
//注:这里是可以写逻辑
$返回的数据=$event->当前事件的类的方法;
Log::info('查看日志成功啦!'.$id);
}
}
4加入把事件加入到你要调的方法中去;
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCategoryRequest;
use Event;//
use App\Events\自定义Event;
class 自定义Controller extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Event::fire(new 自定义Event(1));
}
}
好了完事