php - Doctrine entity creation strategy -


when working entities in doctrine it's obvious add "helper" methods entity. take example;

class post {    protected $tags;     public function __construct() {       $this->tags = new arraycollection();    }     public function gettags() {       return $this->tags;    }     public function addtag( $tagname ) {       $tag = new tag();       $tag->setname( $tagname );        $this->gettags()->add( $tag );    } } 

in works , makes clean code:

$post = new post(); $post->addtag('economy'); 

however, becomes more problematic when tag many many relationship , when adding tag post want check if tag exists. e.g. post might not have tag 'economy' adding post new tag post's point of view. however, if tag 'economy' exists in database have problem. want our entity popo possible, i.e. not have references entity managers or repositories.

what strategy solve problem?

you need outside entity. example...

class post {     // ...      public function addtag(tag $tag) {         $this->gettags()->add($tag);     } } 

and in say, controller...

$post = new post();  // can't remember if returns null no records found or throws // exception. needs checking $tag = $em->getrepository('tag')->findonebyname('economy'); if ($tag == null) {     $tag = new tag();     $tag->setname('economy');      $em->persist($tag); // don't need if use cascade persist } $post->addtag($tag); 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -