我可以覆盖使用者类中的PHP特征属性以使用Doctrine2注释吗?
我正在使用traits在Symfony应用程序中实现一些Taggable行为,使用Doctrine2进行持久化,并使用注释来配置它.
我的主要烦恼是,在特性中,我的IDE不知道$this->标签的类型,并引发了一堆警告.关于在这里记录我的代码我是非常强烈的OCD,所以其他开发人员很容易接受. trait TaggableMethods { /** @var DoctrineCommonCollectionsCollection */ 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 DoctrineCommonCollectionsCollection * @ORMManyToMany(targetEntity="Tag") * @ORMJoinTable(name="ThingA__Tag") */ protected $tags; // <--… because PHP complains about this } class TaggableThingB { use TaggableMethods; /** * @var DoctrineCommonCollectionsCollection * @ORMManyToMany(targetEntity="Tag") * @ORMJoinTable(name="ThingB__Tag") */ protected $tags; } 据我所知,我的问题是我无法在特征中定义$tags属性,因为我需要覆盖注释. 我可以避免在TaggableMethods中定义$tag,但对我来说,这会破坏封装,或者至少使代码更难以阅读. 我可以使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |