Laravel事件Event

適用場景:記錄文章瀏覽量php

php artisan make:event 事件名

示例:html

php artisan make:event MyEvent

Laravel目錄\app\Events已經生成MyEvent.php文件數組

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MyEvent extends Event
{
    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}

事件必須有監聽者,咱們先在\app\Providers目錄下找到EventServiceProvider.php文件,該文件內有一個Events-Listeners數組來保存事件和監聽者的映射關係。bash

protected $listen = [
	'App\Events\MyEvent' => [
		'App\Listeners\MyListener1',
		'App\Listeners\MyListener2'
	]
];

這裏,咱們讓一個事件有兩個監聽者,使用artisan控制檯自動生成php文件app

php artisan event:generate

Laravel\app\Listeners目錄下已經生成了MyListener1.php和MyListener2.phpide

問題來了,咱們怎麼觸發這個事件?函數

這裏借用咱們上一篇博客說的Console,來測試這個事件,若是你對Console不熟,能夠看http://www.cnblogs.com/sweng/p/6358919.html測試

對Check類中修改handle()函數,使用Event::fire(new MyEvent())觸發事件,其實是傳入一個Event對象spa

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

//
use Illuminate\Support\Facades\Event;
use App\Events\MyEvent;

class Check extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
		echo 'checking...';
		Event::fire(new MyEvent());
    }
}
相關文章
相關標籤/搜索