Laravel 8 定義事件

2021-07-14 14:38 更新

事件類是一個保存與事件相關(guān)信息的容器。例如,假設(shè)我們生成的 OrderShipped 事件接收一個 Eloquent ORM 對象:



namespace App\Events;

use App\Models\Order;

use Illuminate\Broadcasting\InteractsWithSockets;

use Illuminate\Foundation\Events\Dispatchable;

use Illuminate\Queue\SerializesModels;

class OrderShipped

{

    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

    /**

     * 創(chuàng)建一個事件實例

     *

     * @param  \App\Models\Order  $order

     * @return void

     */

    public function __construct(Order $order)

    {

        $this->order = $order;

    }

} 

如你所見,這個事件類中沒有包含其它邏輯。它只是一個已購買的 Order 的實例的容器。如果使用 PHP 的 serialize 函數(shù)序列化事件對象,事件使用的 SerializesModels trait 將會優(yōu)雅地序列化任何 Eloquent 模型。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號