简体   繁体   English

在雄辩模型的构造函数中创建一个作为类变量的闭包

[英]Creation of a closure as class variable in constructor of Eloquent Model

I'm trying to create a lambda-style closure as a dynamically-named class variable, within the constructor of an Eloquent model. 我正在尝试在Eloquent模型的构造函数中创建一个lambda样式的闭包作为动态命名的类变量。

It's working fine when the object is instantiated except for when creating a model (that is to say, read, update, and delete work fine). 实例化对象时工作正常,除了创建模型时(即读取,更新和删除工作正常)。

I can get around the problem by explicitly declaring the class variable prior to instantiating the object, however, this is just a hack, I need to be able to create class variables (as closures) dynamically. 我可以通过在实例化对象之前显式声明类变量来解决该问题,但是,这只是一个hack,我需要能够动态创建类变量(作为闭包)。

The following code works, but fails if I remove the declaration $public foo; 以下代码有效,但是如果删除声明$ public foo,则失败;

public $foo;
public function __construct() {
    $foo = 'foo';
    $this->{$foo} = function ($args) { return 'foo';};
}

I'm getting the following error: 我收到以下错误:

exception 'ErrorException' with message 'Object of class Closure could not be converted to string' in /Users/Sites/.../vendor/laravel/framework/src/Illuminate/Support/helpers.php:900 /Users/Sites/.../vendor/laravel/framework/src/Illuminate/Support/helpers.php:900中的消息“类关闭类的对象无法转换为字符串”消息的异常“ ErrorException”

Like I mentioned, this only occurs when creating/inserting an object (sorry if that sounds vague but anyone familiar with Laravel should know what I mean)... instantiating a model in other circumstances (read/update/delete) works just fine. 就像我提到的那样,这仅在创建/插入对象时发生(对不起,如果听起来含糊,但是熟悉Laravel的任何人都应该知道我的意思)...在其他情况下实例化模型(读取/更新/删除)也可以。 Any ideas as to what might be causing the problem would be greatly appreciated! 任何有关可能导致问题的想法,将不胜感激!

Override setAttribute and getAttribute on your model: 在模型上覆盖setAttributegetAttribute

protected $closures = [];

public function setAttribute($key, $value)
{
    if ($value instanceof \Closure)
    {
        $this->setClosureProperty($key, $value);
    }

    parent::setAttribute($key, $value);
}

public function getAttribute($key)
{
    if (array_key_exists($key, $this->closures)
    {
        return $this->closures[$key];
    }

    return parent::getAttribute($key);
}

public function setClosureProperty($key, \Closure $value)
{
    $this->closures[$key] = $value;
}

This way the cloures won't be saved in the attributes array, thus won't be saved and cast to string. 这样,cloures将不会保存在attributes数组中,因此也不会保存并转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM