Entity getter中的未定义索引,即使索引是在构造函数中定义的

时间:2013-08-15 10:58:32

标签: php arrays symfony doctrine-orm entity

我有一个包含以下信息的实体类:

class A
{
    ...
    private $share_data;
    public function __construct()
    {
        $this->share_data = array(
            'title' => null,
            'text' => null,
            'image' => null,
            'tab_image' => null
        );
    }
    ...
    public function getTabImage()
    {
        return $this->share_data['tab_image'];
    }

当我使用Symfony的表单构建器构建表单时,我使用以下代码:

$builder->add('tab_image', 'text', array('required'=>false, 'mapped'=>true, 'label'=>'a.form.tab.image_url'))

因此,当我尝试运行我的代码时,我收到错误注意:未定义索引:tab_image in ...

我认为这是因为在我的数据库中我的列类型为json_array(称为share_data),因此将调用setShareData。在数据库值中,只有标题,文本和图像字段在json对象中定义。因此,对象可能会被覆盖到没有tab_image键的数组。我尝试通过将setShareData更改为以下内容来解决此问题:

public function setShareData($shareData)
{
    // merge so that null values are default
    $this->share_data = array_merge($this->share_data, $shareData);

    return $this;
}

希望它能保留在构造函数中设置的tab_index键。但我仍然收到Undefined索引错误。有什么方法可以将tab_image键设置为null,如果没有设置它?

我想解决这个问题,以便我可以向数组/ json对象添加新键,而无需检查每个getter中是否存在isset。显然,新创建的对象获取了tab_image键,但我希望这是向后兼容的。

2 个答案:

答案 0 :(得分:0)

你有一个拼写错误,试试__construct,你错过了

答案 1 :(得分:0)

你是从数据库中提取这个实​​体吗?

Doctrine在对对象进行保湿时不会调用构造函数。这有点神奇,但属性直接设置。事实上,在水化过程中也不会调用setSharedData。

您可以收听postLoad生命周期事件(http://docs.doctrine-project.org/en/latest/reference/events.html

做类似的事情:

private function getSharedDataTemplate()
{
    return array(
        'title' => null,
        'text' => null,
        'image' => null,
        'tab_image' => null
    );
}
public function __construct()
{
    // For new'ing objects
    $this->share_data = $this->getSharedDataTemplate();
}
/** @PostLoad */
public function doStuffOnPostLoad()
{
    // merge so that null values are default
    $this->share_data = array_merge($this->getSharedDataTemplate(), $this->share_data);
    return $this;
}

您也可以通过设置某种标志来使其工作,并始终检查是否需要合并数据。但生命周期方法会更清晰。

相关问题