0

This is a simple question since I am a noob. I am learning how to use doctrine in a mvc design pattern and I always seem to get confused as to where I should put my code that queries the entities. I have a method to query the entity users, where should it go? Should it be put in my entity, controller, or a repository?

My code:

ENTITY Users

<?php

namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity(repositoryClass="Entities\UserRepository") 
 *  @Table(name="users")
 */
 class Users {

/** @id @column */
protected $id;

/** @column */
protected $first;

/** @column */
protected $mi;

/** @column */
protected $last;

/** @column */
protected $userName;

/** @column */
protected $avatar;

/** @OneToMany(targetEntity="Blog", mappedBy="user") */
protected $blogs;

// Constructor
public function __construct() {
    $this->blogs = new ArrayCollection();
}

public function __get($property) {
    return $this->$property;
}

public function __set($property, $value) {
    $this->$property = $value;
}
}

Method to get users: Where should it go?

public function getUsers(){
    $query = $this->_em->createQuery('SELECT u FROM Entities\Users u');
    return $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
}
reagan
  • 131
  • 1
  • 3
  • 13
  • Doctrine entities should be part of the Model layer and not interacted directly from controller. Maybe [this](http://stackoverflow.com/a/5864000/727208) would shed some light, especially since Doctrine implement data mapper pattern (or something fairly close to it). Basically, the method to retrieve users should go in services, but is see no point in using an ORM, if you are writing pure SQL queries. – tereško Aug 15 '12 at 14:31

1 Answers1

0

The best approach is to use the RepositoryClass and add your custom method there the advantage is that when we use the repository class is that you don't have to redefine the find method

http://mackstar.com/blog/2010/10/04/using-repositories-doctrine-2

user985813
  • 58
  • 1
  • 8