2017-06-19 104 views
0

我想在模型删除后挂钩模型事件以执行任务。我已经添加以下代码,以我的模型:如何将函数名称传递给Laravel 5中的模型事件回调

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

    static::deleted('static::removeStorageAllocation'); 
} 

而不是把我想在开机功能,这似乎是一个相当难看的斑点它封闭内运行的逻辑,我在方法签名注意到它应该是“\ Closure | string $ callback”有没有一种方法可以指定一个函数名称,就像我上面试过的那样?我似乎无法提出任何有效的方法。我试过很多的组合:

'self::removeStorageAllocation' 
'static::removeStorageAllocation' 
'\App\MyModel::removeStorageAllocation' 

我知道我可能只需要指定一个封闭这就要求我的功能,但我想知道什么$回调的字符串形式是?

+0

如果它是一种方法,你可能想添加()结束static :: removeStorageAllocation() –

+0

我得到了同样的错误:ReflectionException与消息'Class static :: removeStorageAllocation()不存在' 这似乎laravel框架期待一个类而不是方法。此外,该函数实际上有一个参数作为引发删除事件的模型的引用 – madz

回答

1

你可以只通过一个匿名函数:

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

要知道$回调的字符串表示,你可以看看删除来源:

/** 
* 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); 
    } 
} 

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

+0

感谢您的回复,但正如我在问题中所说的:“我知道我可能只是指定了一个调用我的函数的闭包,但我'想知道$回调的字符串形式是什么?“ – madz

+0

@madz只需跟踪代码即可。我提供了一个更新。 – Devon

+0

谢谢你,我尝试跟踪代码,但有点迷路,相当新的PHP(和laravel)。干杯 – madz

相关问题