php - 我可以覆盖消费者类中的 PHP 特征属性以使用 Doctrine2 注释吗?

标签 php symfony doctrine-orm annotations traits

我正在使用特征在 Symfony 应用程序中实现一些可标记的行为,使用 Doctrine2 实现持久性,并使用注释来配置它。

我的主要烦恼是,在特征中,我的 IDE 不知道 $this-> 标签的类型,并抛出一堆警告。我对在此处记录我的代码非常强制症,这样其他开发人员就很容易上手。

trait TaggableMethods {
    /** @var \Doctrine\Common\Collections\Collection */
    protected $tags; // <-- Can't seem to define here…
    public function addTag(Tag $tag) {
        $this->tags->add($tag);
    }
    public function removeTag(Tag $tag) {
        $this->tags->removeElement($tag);
    }
    public function getTags() {
        return $this->tags;
    }
}

class TaggableThingA {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingA__Tag")
     */
    protected $tags; // <--… because PHP complains about this
}

class TaggableThingB {
    use TaggableMethods;
    /**
     * @var \Doctrine\Common\Collections\Collection
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="ThingB__Tag")
     */
    protected $tags;
}

据我所知,我的问题是我无法在特征中定义 $tags 属性,因为我需要覆盖注释。

我可以完全避免在 TaggableMethods 中定义 $tags,但对我来说,这会破坏封装,或者至少会使代码更难阅读。

我可以使用 Yaml 或 XML 配置持久性,但我的所有其他实体都使用注释。

所以我正在寻找一种方法来避免生成运行时通知,Symfony 将其转换为 ContextErrorException,从而在开发过程中杀死我的脚本。

这可能与“can we use traits to map manyToOne relationship with doctrine2?”和“Traits - property conflict with parent class”有关

此外,“PHP 5.4: why can classes override trait methods with a different signature? ”中提到的继承方法的行为听起来非常接近我想要的属性 - 谁能解释为什么属性和方法之间存在差异?

最佳答案

您不能覆盖特征,但可以重命名它。

这里有一个例子!

https://github.com/slimphp/Slim/blob/3.x/Slim/App.php#L47-L50

关于php - 我可以覆盖消费者类中的 PHP 特征属性以使用 Doctrine2 注释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31854377/

相关文章:

javascript - 如何将 PHP 内容放入 iframe 中?

php - 在mysql中使用group by查询和order by查询进行选择

symfony - 表单提交成功后如何清除表单值

symfony - Heroku 可信代理

php - 更改 PHP 的控制台输出

php - Symfony2源代码加密/编码

doctrine-orm - 使用 Doctrine 在 Symfony3 中实现好友关系

php - Doctrine : how to use Replace function

symfony - 使用 Doctrine 的 PreUpdate 生命周期事件保留对文档所做的更改

php - MariaDB 无效参数号 : parameter was not defined