问题
In Symfony v3.2, I'm using a form with several EntityType fields, which have hundreds of options - and each option is a relatively big object. Since they don't change so often, I'd like to use some Cache in Symfony, to load them once and just keep feeding the EntityType with it.
I've already cut down the size of the data that's feeding it, by pulling just the fields that I need, and then saved that into a cache.
When I pull the data from cache - I cannot feed it directly to EntityType with a choice_list
, because it gets detached from ObjectManager, and I get an error ("Entities passed to the choice field must be managed").
To re-attach it, I could use the ObjectManager->merge(), but then it means doing a call to DB for each item being re-merged and re-attached to the Manager. That beats the purpose of Caching.
What is the best way to proceed in this scenario? Just lose the EntityType completely from the Form (for speed-sensitive pages) and go with the ChoiceType (which would also include changing the logic in many parts of code)? Anything nicer than that?
So far I didn't find anything near to solution on SO or elsewhere.
回答1:
I've ran into the same question when profiling my forms. One of the problems I faced is that adding Second level caching is very easy when using the QueryBuilder
, but the EntityRepository
methods don't use that cache out of the box.
The solution was actually pretty simple. Just add some cache settings to your query_builder
. Here an example from the Symfony documentation:
$builder->add('users', EntityType::class, array(
'class' => User::class,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
//add something like this
->setCacheable(true)
->setCacheMode(Cache::MODE_NORMAL)
->setCacheRegion('default')
->orderBy('u.username', 'ASC');
},
'choice_label' => 'username',
));
Don't forget to add the second level cache to your entity:
/**
* @ORM\Entity
* @ORM\Cache(region="default", usage="NONSTRICT_READ_WRITE")
*/
class User
{
}
来源:https://stackoverflow.com/questions/43185050/symfony-form-entitytype-caching