laravel使用event

193 阅读1分钟
  1. service_clue/app/Events/TestEvent.php 新建event
<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;

class TestEvent extends Event
{
    use SerializesModels;

    public $data;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}
  1. 调用事件
$params = [
   "name" => 123,
];
$res = \Event::fire(new TestEvent($params));
dd($res);
  1. service_clue/app/Listeners/ClueEventListener.php 配置subscribe listen
$events->listen(
    'App\Events\TestEvent',
    'App\Listeners\ClueEventListener@onTestEvent'
);
  1. 当前类 实现配置方法==>逻辑操作
public function onTestEvent(TestEvent $test){
    var_dump($test->data);
    echo 'end'.PHP_EOL;
    return true;
}

output:

array(1) { ["name"]=> int(123) } end
array:1 [▼
  0 => true
]