symfony2 Doctrine Entity Repository Creating a new Repository


You can create a new Repository where ever you want, but it's recommended to create them in a seperate Repository folder.

While you could name the Repository file and class as you wish, it's recommended to name the Repository EntityNameRepository, to that you could quickly find those in your folder.

Let's assume we have an Project Entity, stored in AppBundle\Entity, it would look like this:

namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

 * Project Entity - some information 
 * @ORM\Table(name="project")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProjectRepository")
class Project
   // definition of the entity with attributes, getters, setter whatsoever

The important part here is the line @ORM\Entity(repositoryClass="AppBundle\Repository\ProjectRepository"), because it connects this Entity with the given Repository class.

Also you need to use the \Doctrine\ORM\Mapping class to use the mapping options.

The repository itself is pretty simple


namespace AppBundle\Repository;

class ProjectRepository extends \Doctrine\ORM\EntityRepository
    public function getLastTenProjects()
        // creates a QueryBuilder instance
        $qb = $this->_em->createQueryBuilder()
            ->from($this->_entityName, 'p')
            ->orderBy('', 'DESC')
        // uses the build query and gets the data from the Database
        return $qb->getQuery()->getResult();


It's important to notice that the Repository class must extend the \Doctrine\ORM\EntityRepository, so that it can work properly. Now you can add as many functions for different querys as you want.