简体   繁体   English

Laravel 4雄辩的模型观察者事件的顺序

[英]Order of Laravel 4 Eloquent Model Observer Events

According to http://laravel.com/docs/eloquent#model-observers the following events are being fired when creating a new item. 根据http://laravel.com/docs/eloquent#model-observers ,创建新项目时会触发以下事件。 creating then created then saving then saved . 创建然后创建然后保存然后保存

However when I do call a model class, the events are being fired the other way round. 但是,当我确实调用模型类时,事件正以相反的方式触发。 Saving is called before creating. 创建之前调用保存。

My Code: 我的代码:

class TBone extends Eloquent {

    protected $table = 'bone';

    protected $primaryKey = 'id';

    protected $guarded = array('id');

}

The Observer Class: 观察者类:

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";
    }
}

The Test: 考试:

class EloquentTest extends TestCase {

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

}

Output when running the Test Case: 运行测试用例时的输出:

saving
creating

So I am just wondering why the saving event is fired before the creating event? 所以我想知道为什么在创建事件之前触发了保存事件? Or am I missing something ? 还是我错过了什么?

Not sure if it's a bug or feature, but you are right, according to the code, create calls save : 不确定是错误还是功能,但是您是对的,根据代码, 创建调用save

public static function create(array $attributes)
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

And save fire the event: 保存事件:

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;
    }

            ....

Before performing insert (create): 在执行插入 (创建)之前:

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

Which fires the creating event 触发创建事件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM