我正在使用特征在 Symfony 应用程序中实现一些可标记的行为,使用 Doctrine2 进行持久化,并使用注释来配置它。
我的主要烦恼是在 trait 中,我的 IDE 不知道 $this->tags 的类型,并抛出一堆警告。我非常强迫症在这里记录我的代码,以便其他开发人员很容易上手。
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;
/** …Run Code Online (Sandbox Code Playgroud)