Symfony 2.5: General pattern and structure to use custom repositories and an overview of EAV database tables

Here is the general code pattern to build a form with a choice sub-object and use a custom repository in Symfony.  The data is stored in an “EAV” table (Entity, Attribute, Value) which is a scalable table modeled after Magento that stores different related data.  For instance, a list of all states and their abbreviations.  How about other choices you use throughout your website that you need to build form select lists from?  Use EAV tables.

I like to build different EAV tables that are basically the same except hold different type of values, so “eav_main_vc25” holds values only up to VARCHAR(25).  By separating EAVs into more manageable and like data units, you keep the tables clean and optimized.


//inside your form

$builder->add(‘general_list_of_things’,’choice’,
array(
‘choices’=>$this->em->getRepository(‘MainFormBundle:choiceListTable’)->getChoiceListTableElements($this->em),
‘attr’=>array(‘class’=>’col-xs-6 col-sm-3′),
‘label_attr’=>array(‘class’=>’col-xs-6 col-sm-3′)
));

Then in the custom repository function:


// Example for custom query inside “ChoiceListRepository", a custom function called "getChoiceList()"

This works here in repo, but you need to pass in the Entity Manager through DIC this way:
/*
$dql = “SELECT c.val from \Main\MainBundle\Entity\EavMainVc25 c
WHERE c.attr = ‘choice_list’ AND c.showLive=’1′ ORDER BY c.entityRef ASC”;
$results = $this->em->createQuery($dql)->getArrayResult();
*/

// This is better — no reason to pass the Entity Manager through DIC:

$dql = “SELECT c.val from \Main\MainBundle\Entity\EavMainVc25 c
WHERE c.attr = ‘choice_list’ AND c.showLive=’1′ ORDER BY c.entityRef ASC”;

$results=$this->_em->createQuery($dql)->getArrayResult();
return $results;

This is another pattern that is frequently accessed, so feel free to use this as a template for your own projects inside AND outside of Symfony.

– Aaron Belchamber

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *