laravel 挂钩到 Eloquent 前和后保存每个模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14902231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:34:07  来源:igfitidea点击:

laravel hook into Eloquent pre and post save for every model

phplaraveleloquent

提问by David

I'm new to Laravel and ORM's in general. How could i hook into Eloquent to fire code before and after a save of any model? I know i can do the following for specific models but i'm looking at figuring out how to do this for every model.

我是 Laravel 和 ORM 的新手。我怎么能在保存任何模型之前和之后连接到 Eloquent 来触发代码?我知道我可以对特定模型执行以下操作,但我正在研究如何为每个模型执行此操作。

class Page extends Eloquent {

   public function save()
   {
      // before save code 
      parent::save();
      // after save code
   }
}

采纳答案by Blessing

You can create a BaseModel class that extends eloquent and then have all your models extend BaseModel. Here's an example:

您可以创建一个扩展 eloquent 的 BaseModel 类,然后让所有模型都扩展 BaseModel。下面是一个例子:

abstract class Elegant extends Eloquent{

/* Save ****************************/
public function preNew() {}
public function postNew() {}
public function preSave() { return true; }
public function postSave() {}
public function save($validate=true, $preSave=null, $postSave=null)
{
    $newRecord = !$this->exists;
    if ($validate)
        if (!$this->valid()) return false;
    if($newRecord)
        $this->preNew();

    $before = is_null($preSave) ? $this->preSave() : $preSave($this);
      // check before & valid, then pass to parent
    $success = ($before) ? parent::save() : false;
    if ($success)
        is_null($postSave) ? $this->postSave() : $postSave($this);
    if($newRecord)
        $this->postNew();
    return $success;
}
public function onForceSave(){}
public function forceSave($validate=true, $rules=array(), $messages=array(), $onForceSave=null)
{
    if ($validate)
        $this->valid($rules, $messages);
     $before = is_null($onForceSave) ? $this->onForceSave() : $onForceSave($this);  // execute onForceSave
     return $before ? parent::save() : false; // save regardless of the result of validation
}

/** Soft Delete ****************************/
public function preSoftDelete() {  return true;  }
public function postSoftDelete()  { }
public function softDelete($val = true, $preSoftDelete=null, $postSoftDelete=null)
{
    if ($this->exists)
    {
        $before = is_null($preSoftDelete) ? $this->preSoftDelete() : $preSoftDelete($this);
        $success = null;
        if($before) {
            $this->set_attribute(static::$softDelete, $val);
            $success = $this->save(false);
        }
        else
            $success = false;
        if ($success)
        {
            is_null($postSoftDelete) ? $this->postSoftDelete() : $postSoftDelete($this);
         }
        return $success;
    }
}

/** Hard Delete ****************************/
public function preDelete()  { return true;}
public function postDelete(){}
public function delete( $preDelete=null, $postDelete=null)
{
    if ($this->exists)
    {
        $before = is_null($preDelete) ? $this->preDelete() : $preDelete($this);
        $success = ($before) ? parent::delete() : false;
        if ($success)
        {
            is_null($postDelete) ? $this->postDelete() : $postDelete($this);
         }
        return $success;
    }
}
}

回答by Niklas Ekman

There's even a better way of accomplishing this! Create an observer for, lets say a model called House:

甚至还有更好的方法来实现这一点!创建一个观察者,假设一个名为 的模型House

class HouseObserver {

    public function saving(House $house) {
        // Code before save
    }

    public function saved(House $house) {
        // Code after save
    }

}

Now register the observer with the Housemodel by adding the line House::observe(new HouseObserver)somewhere. The line can be added in the boot method of the model:

现在House通过在House::observe(new HouseObserver)某处添加行来向模型注册观察者。该行可以添加到模型的引导方法中:

class House extends Eloquent {

    // Lots of model code

    public static function boot() {
        parent::boot();
        self::observe(new HouseObserver);
    }

}

More info can be found here.

可以在此处找到更多信息。

回答by siddhant sankhe

Using laravel models own life cycle events may solve this easy

使用 Laravel 模型自己的生命周期事件可以轻松解决这个问题

/**
 * model life cycle event listeners
 */
public static function boot(){
    parent::boot();

    static::creating(function ($instance){
        //
    });

    static::created(function ($instance){
        //
    });
}