Laravel事件Event


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

php artisan make:event 事件名

示例:

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數組來保存事件和監聽者的映射關系。

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

這里,我們讓一個事件有兩個監聽者,使用artisan控制台自動生成php文件

php artisan event:generate

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

問題來了,我們怎么觸發這個事件?

這里借用我們上一篇博客說的Console,來測試這個事件,如果你對Console不熟,可以看http://www.cnblogs.com/sweng/p/6358919.html

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

<?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());
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM