【问题标题】:How Are Observers Called in Laravel4?Laravel4 中如何调用观察者?
【发布时间】:2016-12-28 20:05:50
【问题描述】:

我正在尝试在 Laravel 4 中创建一个日志系统,在该系统中,只要模型执行保存、更新或删除,我就可以将其记录到数据库中。但是读完这样的教程后我有点困惑:

https://bosnadev.com/2014/12/28/laravel-model-observers/

观察者怎么称呼?模型如何知道何时解雇他们?我对实施工作感到困惑。

【问题讨论】:

  • 也许你正在考虑事件
  • 所以laravel中的观察者模式被称为事件
  • 我觉得大部分材料都解释了here
  • 不,观察者模式不称为事件;但事件可能是您想做的适当的功能

标签: php laravel laravel-4 observer-pattern


【解决方案1】:

即使在 Laravel 4 中,您也可以为这些功能使用它自己的观察者:

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model as Eloquent;

class BaseModel extends Eloquent
{
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->saving(function() {
            \Log::info('saving model '.get_class($this));
        });

        $this->updating(function() {
            \Log::info('updating model '.get_class($this));
        });

        $this->deleteing(function() {
            \Log::info('deleteing model '.get_class($this));
        });
    }
}

你也有保存、更新和删除的观察者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2015-11-05
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    相关资源
    最近更新 更多