【问题标题】:How to add custom event to a Laravel model如何将自定义事件添加到 Laravel 模型
【发布时间】:2020-02-10 06:53:40
【问题描述】:

我有付款模式,想在付款确认后触发自定义事件。

我的型号代码:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $dates = [
        'created_at', 'updated_at', 'confirmed_at',
    ];

    public function confirmed(){
        $this->setAttribute('confirmed_at', now());
        $this->setAttribute('status', 'confirmed');
    }
}

【问题讨论】:

    标签: laravel laravel-5 eloquent laravel-events


    【解决方案1】:

    遇到了这个问题,发现了另一种可能对其他人有帮助的方法。

    目前还有一个选项可以利用观察者,而不必创建自定义事件类。

    在您的模型中添加以下属性:

    protected $observables = ['confirmed'];
    

    此属性是 HasEvents 特征的一部分,并将将此事件注册为 eloquent 事件 (eloquent.confirmed: \App\Payment)。

    您现在可以向观察者添加方法:

    public function confirmed(Payment $payment);
    

    您现在可以触发事件并调用观察者方法:

    $this->fireModelEvent('confirmed');
    

    或者在模型之外(因为fireModelEventprotected):

    event('eloquent.confirmed: ' . Payment::class, $payment);
    

    【讨论】:

      【解决方案2】:

      你可以使用Attribute Events:

      protected $dispatchesEvents = [
          'status:confirmed' => PaymentConfirmed::class,
      ];
      

      【讨论】:

        【解决方案3】:

        我可以在Payment-&gt;confirmed() 方法中触发confirmed 事件,如下所示:

            public function confirmed(){
                // todo, throw an exception if already confirmed
        
                $this->setAttribute('confirmed_at', now());
                $this->setAttribute('status', 'confirmed');
        
                // fire custom event
                $this->fireModelEvent('confirmed');
            }
        

        并将自定义事件注册到$dispatchesEvents

         protected $dispatchesEvents = [
                'confirmed' =>  \App\Events\Payment\ConfirmedEvent::class
         ];
        

        完成。 \App\Events\Payment\ConfirmedEvent::class 事件将在模型confirmed() 方法被调用时调用。

        如果confirmed()方法被调用两次,也建议抛出异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-04
          • 2023-03-21
          • 2021-05-21
          • 2021-06-16
          • 1970-01-01
          • 1970-01-01
          • 2022-12-15
          • 2012-11-30
          相关资源
          最近更新 更多