`
dcj3sjt126com
  • 浏览: 1828360 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Lumen写事件

    博客分类:
  • PHP
阅读更多

1.在事件里面定义事件

<?php

/**

 * Created by PhpStorm.

 * User: maxwelldu

 * Date: 2018/2/8

 * Time: 上午12:17

 */

 

namespace App\Events;

 

use Illuminate\Queue\SerializesModels;

use Log;

use rekoon\common\models\Test;

 

class TestEvent extends Event

{

    use SerializesModels;

    public $test;

 

    public function __construct(Test $test)

    {

        Log::info('init Test Event' . json_encode($test));

        $this->test = $test;

    }

 

    /**

     * Get the channels the event should be broadcast on.

     *

     * @return array

     */

    public function broadcastOn()

    {

        return [];

    }

}

 

2.在监听里面添加监听器

<?php

/**

 * Created by PhpStorm.

 * User: maxwelldu

 * Date: 2018/2/8

 * Time: 上午12:18

 */

 

namespace App\Listeners;

 

use Log;

use App\Events\TestEvent;

class TestListener

{

    public function __construct()

    {

    }

    public function handle(TestEvent $event) {

        Log::info('deal Test with : ' . $event->test);

    }

}

 

3.在服务提供者里面添加事件对应监听器的对应关系

<?php

 

namespace App\Providers;

 

use Laravel\Lumen\Providers\EventServiceProvider as ServiceProvider;

 

class EventServiceProvider extends ServiceProvider

{

    /**

     * The event listener mappings for the application.

     *

     * @var array

     */

    protected $listen = [

        'App\Events\SomeEvent' => [

            'App\Listeners\EventListener'

        ],

        'App\Events\TestEvent' => [

            'App\Listeners\TestListener'

        ]

    ];

 

//    protected $subscribe = [

//        'App\Listeners\TestListener'

//    ];

}

 

 

4.在控制器里面触发事件

 /**

     * 创建一个测试对象

     * @param Request $request

     * @return \Illuminate\Http\JsonResponse

     */

    public function createTest(Request $request)

    {

        /**

         * 数据验证

         */

        $this->validate($request, [

            'name' => 'required',

        ]);

 

        // 添加数据

        $car = Test::create($request->all());

        if (!is_null($car)) {

            $test = new Test();

            $test->name = 'maxwelldu';

 

            Log::info('start send test event');

//            event(new TestEvent($test));

            Event::fire(new TestEvent($test));

//            Event::fire(new TestEvent($test));

        }

        return response()->json($car);

    }

 

5.在bootstrap/app.php中启动事件服务提供者

$app->register(App\Providers\EventServiceProvider::class);

 

6.触发这个控制器的方法,在postman里面请求

 

7.查看storage/logs/lumen.log里面是否有打印的日志信息

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics