Laravel事件Event
適用場(chǎng)景:記錄文章瀏覽量
php artisan make:event 事件名示例:
php artisan make:event MyEventLaravel目錄\app\Events已經(jīng)生成MyEvent.php文件
<?phpnamespace 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 [];} }事件必須有監(jiān)聽(tīng)者,我們先在\app\Providers目錄下找到EventServiceProvider.php文件,該文件內(nèi)有一個(gè)Events-Listeners數(shù)組來(lái)保存事件和監(jiān)聽(tīng)者的映射關(guān)系。
protected $listen = ['App\Events\MyEvent' => ['App\Listeners\MyListener1','App\Listeners\MyListener2'] ];這里,我們讓一個(gè)事件有兩個(gè)監(jiān)聽(tīng)者,使用artisan控制臺(tái)自動(dòng)生成php文件
php artisan event:generateLaravel\app\Listeners目錄下已經(jīng)生成了MyListener1.php和MyListener2.php
問(wèn)題來(lái)了,我們?cè)趺从|發(fā)這個(gè)事件?
這里借用我們上一篇博客說(shuō)的Console,來(lái)測(cè)試這個(gè)事件,如果你對(duì)Console不熟,可以看http://www.cnblogs.com/sweng/p/6358919.html
對(duì)Check類中修改handle()函數(shù),使用Event::fire(new MyEvent())觸發(fā)事件,實(shí)際上是傳入一個(gè)Event對(duì)象
<?phpnamespace 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());} }
轉(zhuǎn)載于:https://www.cnblogs.com/sweng/p/6358961.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見(jiàn)證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Laravel事件Event的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: struts2常用标签
- 下一篇: CTAssetsPickerContro