实现Laravel Eloquent模型事件 - 检查已触发的事件

时间:2016-05-15 23:55:04

标签: php laravel laravel-5 eloquent

我正在回答这个问题:

Laravel Model Events

我正在尝试实现标记答案的代码。

我认为每一个想法都是“答案”,但它似乎并没有解雇事件。

如何检查事件是否正在触发?

这是我的模特:

<?php

namespace App;

use App\Traits\ModelEventThrower;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Cuotas extends Model
{
    use ModelEventThrower;


    protected $fillable = [ 'apartamento_id','fecha_cuota','fecha_vencimiento', 'tipo_cuota_id', 'monto', 'descripcion_cuota','saldo'  ];
    protected $dates = ['created_at', 'updated_at', 'deleted_at','fecha_vencimiento','fecha_cuota'];
    protected $appends = ['tipo_cuota'];

    //protected static $othersEvents = ['saving'];



    function getTipoCuotaAttribute(){
        $id = $this->attributes['tipo_cuota_id'];
        $tipoCuota = TipoCuota::lists('descripcion_cuota','id')->toArray();
        return $tipoCuota[$id];
    }


    function getFechaVencimientoAttribute($value){
        return Carbon::parse($value)->format('d-m-Y');
    }
    function setFechaVencimientoAttribute($value){
        $this->attributes['fecha_vencimiento'] = Carbon::createFromFormat('d-m-Y', $value);
    }

    function getFechaCuotaAttribute($value){
        return Carbon::parse($value)->format('d-m-Y');
    }
    function setFechaCuotaAttribute($value){
        $this->attributes['fecha_cuota'] = Carbon::createFromFormat('d-m-Y', $value);
    }

    function apartamento()
    {
        return $this->belongsTo('App\Apartamentos', 'apartamento_id');
    }
    public function pagos(){
        return $this->hasMany('App\Pagos','cuota_id', 'id');
    }
}

这是我的特质:

<?php

namespace App\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;

/**
 * Class ModelEventThrower
 * @package App\Traits
 *
 *  Automatically throw Add, Update, Delete events of Model.
 */
trait ModelEventThrower {

    /**
     * Automatically boot with Model, and register Events handler.
     */
    protected static function bootModelEventThrower()
    {

        foreach (static::getModelEvents() as $eventName) {
            static::$eventName(function (Model $model) use ($eventName) {
                try {
                    $reflect = new \ReflectionClass($model);
                    Event::fire(strtolower($reflect->getShortName()).'.'.$eventName, $model);
                } catch (\Exception $e) {
                    return true;
                }
            });
        }
    }

    /**
     * Set the default events to be recorded if the $recordEvents
     * property does not exist on the model.
     *
     * @return array
     */
    protected static function getModelEvents()
    {
        if (isset(static::$othersEvents)) {
            return static::$othersEvents;
        }

        return [
            'created',
            'updated',
            'deleted',
        ];
    }
} 

我的EventServiceProvider:

<?php

namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [ 'App\Listeners\EventListener', ],
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
        $events->subscribe('App\Handlers\Events\CuotasEventHandler');
    }
}

我的事件处理程序:

<?php

namespace App\Handlers\Events;

use App\Cuotas;

class CuotasEventHandler{

    /**
     * Create the event handler.
     *
     * @return \App\Handlers\Events\CuotasEventHandler
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle cuotas.created event
     */

    public function created(Cuotas $cuotas)
    {
       dd('created');
    }

    /**
     * Handle cuotas.updated event
     */

    public function updated(Cuotas $cuotas)
    {
        //Implement logic
        dd('updated');
    }

    /**
     * Handle cuotas.deleted event
     */

    public function deleted(Cuotas $cuotas)
    {
        //Implement logic
        dd('deleted');
    }

    /**
     * @param $events
     */
    public function subscribe($events)
    {
        $events->listen('cuotas.created','App\Handlers\Events\CuotasEventHandler@created');
        $events->listen('cuotas.updated','App\Handlers\Events\CuotasEventHandler@updated');
        $events->listen('cuotas.deleted','App\Handlers\Events\CuotasEventHandler@deleted');

    }

}

当我更新,删除或创建模型$ Cuotas中的新记录时,我无法看到该事件是否被解雇。

我的目的是使用已在其他模型“pagos”中完成的付款更新模型的“saldo”(余额)列。

1 个答案:

答案 0 :(得分:0)

一些方法,重新启动服务器后,事件会自动启动。