laravel事件&订阅
1、事件&订阅 理解
-
理解:打工
我(订阅者)今天去打工,上午去跑摩的(事件1),下午去送外卖(事件2)
-
监听和订阅的区别就是,1个监听只对应1个事件,1个订阅可对应多个事件。
-
以下例子:操作库存(订阅),采购商品-增加库存(事件1),用户下单-扣减库存(事件2)
2、生成事件和订阅
php artisan event:generate
#执行后会生成`app/Events`和`app/Listeners`目录
php artisan make:event IncreaseStockEvent
#生成事件1 -- 增加库存
php artisan make:event ReduceStockEvent
#生成事件2 -- 扣减库存
php artisan make:listener StockSubscribe
#生成订阅者 -- 操作库存
3、注册订阅者
- app/Providers/EventServiceProvider.php
/**
* 需要注册的订阅者类。
* @var array
*/
protected $subscribe = [
'App\Listeners\StockSubscribe',
];
4、为订阅者绑定事件
- app/Listeners/StockSubscribe.php - 新增subscribe方法
public function subscribe($events) {
$events->listen(
'App\Events\IncreaseStockEvent',
'App\Listeners\StockSubscribe@onIncreaseStock'
);
$events->listen(
'App\Events\ReduceStockEvent',
'App\Listeners\StockSubscribe@onReduceStock'
);
}
5、事件参数
- app/Events/IncreaseStockEvent.php
<?php
namespace App\Events;
//... ...
class IncreaseStockEvent
{
//... ...
public $userName;
public $goodsSn;
public $qty;
public function __construct(string $userName, string $goodsSn, int $qty)
{
$this->userName = $userName;
$this->goodsSn = $goodsSn;
$this->qty = $qty;
}
}
- app/Events/ReduceStockEvent.php
<?php
namespace App\Events;
//... ...
class ReduceStockEvent
{
//... ...
public $userName;
public $goodsSn;
public $qty;
public function __construct(string $userName, string $goodsSn, int $qty)
{
$this->userName = $userName;
$this->goodsSn = $goodsSn;
$this->qty = $qty;
}
}
6、订阅者增加业务处理-库存操作
- app/Listeners/StockSubscribe.php
<?php
namespace App\Listeners;
use App\Events\IncreaseStockEvent;
use App\Events\ReduceStockEvent;
use Illuminate\Support\Facades\Log;
class StockSubscribe
{
/**
* 为订阅者绑定事件
*
* @param Illuminate\Events\Dispatcher $events
*/
public function subscribe($events) {
$events->listen(
'App\Events\IncreaseStockEvent',
'App\Listeners\StockSubscribe@onIncreaseStock'
);
$events->listen(
'App\Events\ReduceStockEvent',
'App\Listeners\StockSubscribe@onReduceStock'
);
}
/**
* 增加库存
* @param IncreaseStockEvent $event
*/
public function onIncreaseStock(IncreaseStockEvent $event)
{
//--处理业务逻辑
//接收事件参数
$userName = $event->userName ?? '';
$goodsSn = $event->goodsSn ?? '';
$qty = $event->qty ?? 0;
Log::info($userName.' -- '.$goodsSn.' -- '.'增加库存' .' -- '.$qty);
}
/**
* 扣减库存
* @param ReduceStockEvent $event
*/
public function onReduceStock(ReduceStockEvent $event)
{
//--处理业务逻辑
//接收事件参数
$userName = $event->userName ?? '';
$goodsSn = $event->goodsSn ?? '';
$qty = $event->qty ?? 0;
Log::info($userName.' -- '.$goodsSn.' -- '.'扣减库存' .' -- '.$qty);
}
}
7、调用事件触发订阅行为
event(new \App\Events\IncreaseStockEvent('张三','白衬衫',2));
#增加库存
event(new \App\Events\ReduceStockEvent('李四','黑礼服',3));
#扣减库存
8、结果
[2022-05-08 16:22:11] local.INFO: 张三 -- 白衬衫 -- 增加库存 -- 2
[2022-05-08 16:22:13] local.INFO: 李四 -- 黑礼服 -- 扣减库存 -- 3