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


Order of Laravel 4 Eloquent Model Observer Events

根据http://laravel.com/docs/eloquent#model-观察者-创建新项目时将触发以下事件创建,然后创建,再保存然后保存

然而,当我调用一个模型类时,事件会以另一种方式触发。在创建之前调用保存。

我的代码:

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

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

不确定这是错误还是功能,但你是对的,根据代码,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);
    }

触发创建事件

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