Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I include a convenience query in a Doctrine 2 Entity Method?

I'd like to include some additional functions in my Doctrine 2 entities to contain code that I'm going to have to run quite frequently. For example:

User - has many Posts
Post - has a single user

I already have a function $user->getPosts(), but this returns all of my posts. I'm looking to write a $user->getActivePosts(), which would be like:

$user->getPosts()->where('active = true') //if this were possible
or:
$em->getRepository('Posts')->findBy(array('user'=>$user,'active'=>true)) //if this were more convenient

As far as I can tell, there's no way to get back to the entity manager though the Entity itself, so my only option would be

class User {
   function getActivePosts() {
     $all_posts = $this->getPosts();
     $active_posts = new ArrayCollection();
     foreach ($all_posts as $post) {
        if ($post->getActive()) {
           $active_posts->add($post);
        }
     }
     return $active_posts;
}

However, this requires me to load ALL posts into my entity manager, when I really only want a small subset of them, and it requires me to do filtering in PHP, when it would be much more appropriate to do so in the SQL layer. Is there any way to accomplish what I'm looking to do inside the Entity, or do I have to create code outside of it?

like image 639
Andrew Rueckert Avatar asked Aug 04 '11 18:08

Andrew Rueckert


1 Answers

I think you should implement the method on the PostRepository rather than on the entity model.

I try to keep all model related logic in the repositories behind "domain specific" methods. That way if you change the way you represent whether a post is active or not, you only have to change the implementation of a single method instead of having to find all the active = true statements scattered around in your application or making changes in an "unrelated" entity model.

Something like this

PostRepository extends EntityRepository {
  public function findActiveByUser($user){
     // whatever it takes to get the active posts
  }
}
like image 185
Jon List Avatar answered Sep 30 '22 02:09

Jon List