zendframework/zf2 — pull request #4947 by ThomasCantonnet (2013-08-12 09:32:16+00:00)
Title: Allow form caching

Hello,

When using Doctrine2's AnnotationBuilder, I would like to be able to cache the form created from an entity since it is quite slow to build it from annotations (I love them nonetheless). However, some calls in the constructors for Zend\Form make it impossible to cache objects in APC since they do not call the constructors when they are unserialized.

I got rid of one call in the constructor of FilterChain but couldn't in Fieldset since it resulted in a failed test. I do not know if this is the right approach (though I think __wakeup() and __sleep() methods are out of the question IMHO) but this seems to be a light fix for this approach. The tests seem to be ok with this, The removal of the call in FilterChain might break BC when I think about it. Any thoughts ?

Another approach could be implementing a setIterator() method on FieldSet and a setFilters() on FilterChain. I do not know what approach is best, I do not know if this method is better than the other, test-wise.

Here's the problematic code :

```php
public function getForm($entity)
{
$cache = \Zend\Cache\StorageFactory::factory(array(
'adapter' => 'apc',
'plugins' => array(
'exception_handler' => array('throw_exceptions' => false),
),
));

$em = $this->getManager();
$cacheKey = get_class($entity);
$hydrator = new DoctrineHydrator($em, $this->getRepoName());

if ($cache->hasItem($cacheKey)) {
$form = $cache->getItem($cacheKey);
}
else {
$builder = new AnnotationBuilder($em);
$form = $builder->createForm($entity);
$cache->setItem($cacheKey, $form);
}
$form->setHydrator($hydrator);
$form->bind($entity);

return $form;
}