如何在 Laravel 5 中将函数名称传递给模型事件回调



我想在删除模型后挂接模型事件以执行任务。我已将以下代码添加到我的模型中:

protected static function boot()
{
    parent::boot();
    static::deleted( 'static::removeStorageAllocation' );
}

我没有将我想运行的逻辑放在引导函数的闭包中,这似乎是一个非常丑陋的地方,我注意到在方法签名中它应该需要"\Closure|string $callback"有没有办法像我上面尝试的那样指定函数名称?我似乎想不出任何有效的方法。我尝试了很多组合:

'self::removeStorageAllocation'
'static::removeStorageAllocation'
'AppMyModel::removeStorageAllocation'

我知道我可能只指定一个调用我的函数的闭包,但我想知道$callback的字符串形式是做什么的?

你可以只传递一个匿名函数:

static::deleted(function() {
    static::removeStorageAllocation();
});

要了解$callback的字符串表示形式,您可以查看已删除的来源:

/**
 * Register a deleted model event with the dispatcher.
 *
 * @param  Closure|string  $callback
 * @param  int  $priority
 * @return void
 */
public static function deleted($callback, $priority = 0)
{
    static::registerModelEvent('deleted', $callback, $priority);
}

您将看到它正在注册事件侦听器:

/**
 * Register a model event with the dispatcher.
 *
 * @param  string  $event
 * @param  Closure|string  $callback
 * @param  int  $priority
 * @return void
 */
protected static function registerModelEvent($event, $callback, $priority = 0)
{
    if (isset(static::$dispatcher))
    {
        $name = get_called_class();
        static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback, $priority);
    }
}

因此,$callback最终用作侦听器。 字符串表示形式很可能是侦听器类的名称,而不是方法。

在模型上创建一个受保护的或公共的静态函数(私有函数不起作用(:

protected static function myStaticCallback($model)
{
    // Your code
}

然后向模型添加一个引导方法,使用数组作为回调 [class, function]:

protected static function boot()
{
    parent::boot();
    static::creating(['MyModel', 'myStaticCallback']);
}

最新更新