phpro / zf-doctrine-hydration-module

Configurable Doctrine hydrators for ZF2
18 stars 33 forks source link

Default hydrator strategies #4

Closed pietervogelaar closed 10 years ago

pietervogelaar commented 10 years ago

Thanks for this great module! Per hydrator strategies can be defined. As feature request, it would be awesome if default strategies could also be defined that apply to all hydrators.

I use Apigility with Doctrine that makes use of this module. On all fields that are called "created" I want my UtcDateTimeStrategy to be set. So on every hydrator that apigility creates per rest service. I could add this manually in the configuration for every hydrator, but it is likely someone in the development team will forget one in the future.

veewee commented 10 years ago

Hello Pieter,

I think it is better to explicitly configure the strategy per field. This way you know exactly how the hydration works by just looking at the configuration of the hydrator. If you really want to add these 'magic' default strategies to the hydrator, you can use custom hydrator initializers. Here is an example:

Register the initializer to the Hydrator Manager in your config file:

return [
    'hydrators' => [
        'initializers' => [
            'YourNamespace\Hydrator\Initializer\CreatedStrategyInitializer',
        ],
    ],
];

The initializer class:

namespace YourNamespace\Hydrator\Initializer;

use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
use Phpro\DoctrineHydrationModule\Hydrator\DoctrineHydrator;
use Zend\ServiceManager\InitializerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class CreatedStrategyInitializer implements InitializerInterface
{

    public function initialize($instance, ServiceLocatorInterface $serviceLocator)
    {
        if (!($instance instanceof DoctrineHydrator)) {
            return;
        }

        $serviceManager = $serviceLocator->getServiceLocator();
        /** @var DoctrineObject $hydrator */
        $hydrator = $instance->getExtractService();

        if ($hydrator->hasStrategy('created')) {
            $hydrator->removeStrategy('created');
        }

        $hydrator->addStrategy('created', $serviceManager->get('UtcDateTimeStrategy'));
    }
}
pietervogelaar commented 10 years ago

Hi Toon,

Okay, thanks a lot for your detailed answer!

Pieter