laravel 事件监听(自己理解)
2018年9月10日什么是laravel 事件监听?个人理解当控制器的一个方法执行成功就会触发这个绑定的事件,但是要怎么才能知道这个事件有没有触发?所以需要一个监听器,看图
1.创建事件
1 |
php artisan make:event OrderPaid |
编辑事件app\Events\OrderPaid.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Queue\SerializesModels; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use App\Models\Order; class OrderPaid { use Dispatchable, InteractsWithSockets, SerializesModels; /** * 用来存放order模型对象的变量 * @var */ protected $order; /** * Create a new event instance. * * @return void */ public function __construct(Order $order) #这个会返回event对象的 { $this->order = $order; } /** * 获取订单模型 * @return Order */ public function getOrder() { return $this->order; } } |
事件不需要计算业务逻辑,它的主要功能就是,告诉监听器,让监听器执行逻辑,因为监听器可以队列啊
2.创建监听器
注意后面的参数
1 |
php artisan make:listener UpdateProductSoldCount --event=OrderPaid |
编辑监听器app\Listeners\UpdateProductSoldCount.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php namespace App\Listeners; use App\Events\OrderPaid; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use App\Models\OrderItem; class UpdateProductSoldCount implements ShouldQueue #为什么implements SholdQuere 因为要队列啊 { /** * Handle the event. * * @param OrderPaid $event * @return void */ public function handle(OrderPaid $event) #Laravel 会默认执行监听器的 handle 方法,触发的事件会作为 handle 方法的参数,说白了传递的参数还是订单 order { $order = $event->getOrder(); #从事件对象中取出对应的订单 order调用items方法 foreach ($order->items as $item) { #循环遍历订单的商品 $product = $item->product; #product 代表一个子商品 $soldCount = OrderItem::query() #创建一个子订单查询计算对应商品的销量 ->where('product_id', $product->id) #首先要确定商品 ->whereHas('order', function ($query) { #然后调用order方法儿子找爹,找父訂單 $query->whereNotNull('paid_at'); #判断是否支付 })->sum('amount'); $product->update(['sold_count' => $soldCount,]); #更新商品销量 } } } |
3.将事件和控制器绑定
任意一个控制器里的方法,将其绑定
1 2 3 4 5 6 7 8 9 10 11 |
use App\Events\OrderPaid; #引入事件 . . . function store(){ . . . event(new OrderPaid($order)); #开始激活事件 return . . . } |
4. 将事件和监听器绑定
打开app\Providers\EventServiceProvider.php
文件开始编辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
use App\Events\OrderPaid; #引入支付成功事件 use App\Listeners\UpdateProductSoldCount; #引入支付成功监听 class EventServiceProvider extends ServiceProvider { /** * The event listener mappings for the application. * * @var array */ protected $listen = [ OrderPaid::class=>[ UpdateProductSoldCount::class, ], ]; . . . } |