我們使用一個(gè)
post
模型
<?php
namespace App;
use App\Events\PostWasPublished;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $events = [
'created' => PostWasPublished::class , //key就是事件的名字锡垄,值就是觸發(fā)的事件饰潜。這個(gè)事件可以是一個(gè)完整的類(lèi)
];
}
當(dāng)執(zhí)行到這個(gè)model里面created方法的時(shí)候筒扒,會(huì)觸發(fā)PostWasPublished事件裁着。這個(gè)事件也就是PostWasPublished類(lèi)里面的代碼吝梅。它背后的監(jiān)聽(tīng)著,其實(shí)就是PostWasPublishedListenr類(lèi)里面的代碼
然后我們?nèi)?code>EventServiceProvider類(lèi)里面修改
$listen
屬性
protected $listen = [
'App\Events\PostWasPublished' => [
'App\Listeners\PostWasPublishedListenr',
// 如果一個(gè)事件需要發(fā)送給多個(gè)監(jiān)聽(tīng)者,我們只需要把監(jiān)聽(tīng)的類(lèi)寫(xiě)入這個(gè)數(shù)組里面
],
];
此時(shí)執(zhí)行
php artisan event:generate
會(huì)生成兩個(gè)類(lèi)
Events文件
中生成PostWasPublished
類(lèi)舵抹,Listeners文件
中生成PostWasPublishedListenr
類(lèi),也就是上面$listen
屬性定義的兩個(gè)類(lèi)劣砍。
PostWasPublished發(fā)布類(lèi)
<?php
namespace App\Events;
use App\Post;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class PostWasPublished
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $post; // 注意此處要被繼承使用惧蛹,必須用publish
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Post $post)
{
$this->post = $post;
}
/**
* Get the channels the event should broadcast on.
*
* @return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
PostWasPublishedListenr監(jiān)聽(tīng)類(lèi)
<?php
namespace App\Listeners;
use App\Events\PostWasPublished;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class PostWasPublishedListenr
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param PostWasPublished $event
* @return void
*/
public function handle(PostWasPublished $event)
{
// 因?yàn)楸O(jiān)聽(tīng)類(lèi)PostWasPublished里面注入了Pos這個(gè)model類(lèi),所以我們可以直接使用Post里面的函數(shù)
dump($event->post->toArray());
}
}
路由
注意此處用的是 create 而不是created
Route::get('/', function () {
return \App\User::create(['name'=>'name','email'=>'62em11ail3@qq.com','password'=>'password']);
});
也可以直接在路由里使用event全局函數(shù)做觸發(fā)
以下方式跟User的模型里面 $events 屬性就沒(méi)有關(guān)系了刑枝,這是直接觸發(fā)的
這種打方式會(huì)觸發(fā)兩次事件
Route::get('/', function () {
$user = \App\User::create(['name'=>'name','email'=>'652em11ail3@qq.com','password'=>'password']);
event(new \App\Events\PostPublished($user));
});
這種方式會(huì)觸發(fā)一次事件
Route::get('/', function () {
$user = \App\User::find(2);
event(new \App\Events\PostPublished($user));
});
- 但是可以監(jiān)聽(tīng)的事件只有以下函數(shù)中的那些