我正在使用特征在 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? ”中提到的继承方法的行为听起来非常接近我想要的属性 - 谁能解释为什么属性和方法之间存在差异?
最佳答案
关于php - 我可以覆盖消费者类中的 PHP 特征属性以使用 Doctrine2 注释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31854377/