我需要将一个匿名函数传递给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
表示的闭包周围调用chunk:
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
之前处理事件分派器,在这一点上,我甚至可能不尝试合并我的代码)。
谁知道有什么技巧可以让这个工作?
use
关键字允许匿名函数从父作用域继承变量。
class MyModel extends Eloquent {
// ... table stuff
public static function doSomething (Closure $thing) {
$dispatcher = static::getEventDispatcher();
static::unsetEventDispatcher();
// note the use keyword
static::chunk(100, function ($records) use ($thing) {
foreach($records as $model) {
$thing($model); // not set in this scope
}
});
static::setEventDispatcher($dispatcher);
}
}
匿名函数文档。use
关键字如例3所示。