【发布时间】:2015-08-21 21:49:06
【问题描述】:
我需要将匿名函数传递给 Eloquent 模型上的静态方法,并让该静态方法在块闭包中调用闭包。目标是类似于以下的代码:
class MyModel extends Eloquent {
// ... table stuff
public static function doSomething (Closure $thing) {
$dispatcher = static::getEventDispatcher();
static::unsetEventDispatcher();
static::chunk(100, function ($records) {
foreach($records as $model) {
$thing($model); // not set in this scope
}
});
static::setEventDispatcher($dispatcher);
}
}
//...
MyModel::doSomething(function($m){/*some crypto stuff*/});
$thing 未设置,因为它超出了范围。我想知道是否有一些技巧可以使这项工作。目前,我正在使用非静态方法,并围绕$thing 表示的闭包调用块:
class MyModel extends Eloquent {
public function doSomething (Closure $thing) {
// unset event dispatcher
$thing($this);
// reset event dispatcher
}
}
MyModel::chunk(100, function ($records) {
foreach($records as $model) {
$model->doSomething(function($m){/*some crypto stuff*/});
}
}
这是次优的,因为每次我想调用 doSomething 时我都必须编写块循环,并且事件调度程序被删除并为每条记录重置(或者更糟:我必须记住处理事件调用 chunk 之前的调度程序,此时我什至可能不尝试整合我的代码。
任何人都知道可以使这项工作的任何技巧?
【问题讨论】:
标签: php laravel static scope eloquent