Skip to main content
Image for post: Doctrine custom repository on Symfony2

Doctrine custom repository on Symfony2

Here I am with the first post of the 2015. Happy new year! I'm still learning and working with Symfony2 and today I've had some problem about setting a custom repository class that extends a Doctrine entity. Here is the specific page and paragraph on the offcial documentation. They Symfony documentation is great, much better than many other docunentation I've read online. When I've tried to set my own custom class repository, I've generated the class, the namespace was ok but I miss a detail on my doctrine xml configuration. Symfony didn't generated it and the application was showing an error. Untile I've read a good question and answer on stackoverflow. As always stackoverflow can save your life! On your doctrine entity you can extend your class:


/**
* Config
*
* @ORM\Table(...)
* @ORM\Entity(repositoryClass="ModelBundle\Repository\ConfigRepository")
*/
class Config
{
// your code...
}

And then create a class on the namespace specified in @ORM\Entity(). Here you can use the queryBuilder object and access the entity manager:


namespace ModelBundle\Repository;

use ModelBundle\Entity\Config;
use Doctrine\ORM\EntityRepository;

/**
* Class ConfigRepository
*/
class ConfigRepository extends EntityRepository
{
       //...

       /**
        * @return \Doctrine\ORM\QueryBuilder
        */
       private function getQueryBuilder()
       {
           return $this->getEntityManager()
                       ->getRepository('ModelBundle:ZfcmsConfig')
                       ->createQueryBuilder('c');
       }
}

Now you can use this class on your controller but I suggest to create a Manager on your services.yml. The manager will be a sort wrapper:


<?php

namespace ModelBundle\Services;

use Doctrine\ORM\EntityManager;
use ModelBundle\Entity\Config;

/**
* Class ConfigManager
*/
class ConfigManager
{
   private $em;

   /**
    * @param EntityManager $em
    */
   public function __construct(EntityManager $em)
   {
       $this->em = $em;
   }

   /**
    * Find configurations
    *
    * @return array
    */
   public function findConfigs()
   {
       $config = $this->em->getRepository('ModelBundle:Config')->findConfigs();

       return $config;
   }
}

You can configure the manager on your services.yml on app\config\services.yml or on the same file resource of your bundle. But if the generator miss the connection with your doctrine xml file you have to add it manually:


<entity name="ModelBundle\Entity\Config" table="config" repository-class="ModelBundle\Repository\ConfigRepository">

The path will be ModelBundle\Resource\config\doctrine\Config.xml. I hope this will be useful to someone.  

Related articles across the web

Share this post

This website and/or any sub domains use cookies to understand how you to improve your experience.