【问题标题】:Laravel Eloquent: access method parameter within chunk ClosureLaravel Eloquent:在块闭包中访问方法参数
【发布时间】: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


    【解决方案1】:

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

    匿名函数文档hereuse 关键字如示例 3 所示。

    【讨论】:

    • 给你一罐饼干我完全忘记了。
    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多