php - Doctrine ORM - entity implements interface -
i have following problem - in project, have interface called taggableinterface
interface taggableinterface { public function addtag(taginterface $tag); public function deletetag(taginterface $tag); public function gettags(); }
it implemented entity classes.
is there way in doctrine creates relations between entites , tags? if taggable wasn't interface abstarct class, able solve entity inheritance..
without doctrine use party/accountability design pattern (http://martinfowler.com/apsupp/accountability.pdf).
if understood properly: want create mapping , implementation interface without using abstract class , repeating code.
php have traits. can create trait common implementation of interface. experience know can add doctrine annotations mapping trait , work well.
create taggabletrait. behave class or interface. reside in namespace , loaded autoloader if add use
.
namespace my\namespace; use doctrine\orm\mapping orm; trait taggabletrait { /** * @orm\manytomany(targetentity="some\namespace\entity\tag") */ protected $tags; public function addtag(taginterface $tag) { $this->tags->add($tag); } public function removetag(taginterface $tag) { $this->tags->removeelement($tags); } public function deletetag(taginterface $tag) { $this->removetag($tag); } public function gettags() { return $this->tags; } }
and in taggable entity:
namespace some\namespace\entity; use some\namespace\taggableinterface; use my\namespace\taggabletrait; use doctrine\orm\mapping orm; //... /** * @orm\entity */ class taggableentity implements taggableinterface { use taggabletrait; public function __construct() { $this->tags = new arraycollection(); } // rest of class code }
note use
inside class have different meaning. add trait , have nothing namespace importing.
you must initialize $tags
in constructor, trait cannot that.
that way can create unidirectional association. if want more customization, remove mapping trait , add class.