laravel 中 boot 和 booted 的区别

par*_*rth 7 php laravel

我试图了解 boot 和 booted 的用法和区别。

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected static function boot() {
        parent::boot();

        static::creating(function ($user) {

        });
    }

    protected static function booted() {
        parent::booted();

        static::creating(function ($user) {

        });
    }
}
Run Code Online (Sandbox Code Playgroud)

何时何地应该调用这两个函数?

小智 6

实际上答案就在 Eloquent 模型本身中

protected function bootIfNotBooted()
{
    if (! isset(static::$booted[static::class])) {
        static::$booted[static::class] = true;

        $this->fireModelEvent('booting', false);

        static::booting();
        static::boot();
        static::booted();

        $this->fireModelEvent('booted', false);
    }
}
/**
 * Perform any actions required before the model boots.
 *
 * @return void
 */
protected static function booting()
{
    //
}

/**
 * Bootstrap the model and its traits.
 *
 * @return void
 */
protected static function boot()
{
    static::bootTraits();
}

/**
 * Perform any actions required after the model boots.
 *
 * @return void
 */
protected static function booted()
{
    //
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我都试过了,我认为都是一样的;只是它将boot首先运行并且需要调用额外的parent::boot()


protected static function boot()
{
    parent::boot();

    self::creating(function (Outlet $outlet): void {
        Log::debug("#boot");
        $outlet->name = "boot";
    });
    
}

protected static function booted()
{
    self::creating(function (Outlet $outlet): void {
        Log::debug("#booted");
        $outlet->name = "booted";
    });
    
}

Run Code Online (Sandbox Code Playgroud)