【问题标题】:Order of Laravel 4 Eloquent Model Observer EventsLaravel 4 Eloquent 模型观察者事件的顺序
【发布时间】:2014-04-30 23:58:34
【问题描述】:

根据http://laravel.com/docs/eloquent#model-observers,创建新项目时会触发以下事件。 创建然后创建然后保存然后保存

但是,当我调用模型类时,事件会以相反的方式被触发。在创建之前调用保存。

我的代码:

class TBone extends Eloquent {

    protected $table = 'bone';

    protected $primaryKey = 'id';

    protected $guarded = array('id');

}

观察者类:

class ObserverLeBone{

    public function creating($bone)
    {
        echo "creating\r\n";
    }

    public function saving($bone) 
    {
        echo "saving\r\n";
    }

    public function updating($bone) 
    {
        echo "updating\r\n";
    }
}

测试:

class EloquentTest extends TestCase {

    public function testObserver()
    {
       TBone::observe(new ObserverLeBone());
       $attributes = array('appreciatedAs' => 'Steak'); 
       TBone::create($attributes);
    }

}

运行测试用例时的输出:

saving
creating

所以我只是想知道为什么在创建事件之前会触发保存事件? 还是我错过了什么?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    不确定是bug还是功能,但你是对的,根据代码,create调用save

    public static function create(array $attributes)
    {
        $model = new static($attributes);
    
        $model->save();
    
        return $model;
    }
    

    然后保存触发事件:

    public function save(array $options = array())
    {
        $query = $this->newQueryWithDeleted();
    
        // If the "saving" event returns false we'll bail out of the save and return
        // false, indicating that the save failed. This gives an opportunities to
        // listeners to cancel save operations if validations fail or whatever.
        if ($this->fireModelEvent('saving') === false)
        {
            return false;
        }
    
                ....
    

    在执行插入(创建)之前:

        else
        {
            $saved = $this->performInsert($query);
        }
    

    触发creating事件

    if ($this->fireModelEvent('creating') === false) return false;
    

    【讨论】:

    • 是的,它更像是一个术语 clusterf***。我以为。 create 意味着在内存中创建一些东西。保存意味着向数据库中插入一些东西。而 laravel 似乎使用术语 create 作为“插入”。但随后“更新”毫无意义。现在我必须在我的保存事件处理程序中加入逻辑来确定一个对象是否已经被持久化,我认为这是不必要的,因为我有一个创建事件......所以是的,没有错误只是一种解释方式...... .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    相关资源
    最近更新 更多