北京网帮你
laravel5事件与监听使用教程例子
时间:2016-03-29 00:17:13 浏览:407

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));


   }


 



}


好了完事




[上一篇] laravel- cache-缓存,方法使用
[下一篇]bootstrap加offcanvas实现左右弹
Copyright 2022 © 93580.com.cn 网帮你

2022 © 版权所有 红花岗区网帮你信息技术工作室

工信部备案号:黔ICP备2024036985号-2

请使用网帮你微信扫码登录