5

I have pretty much an identical issue as Dependency injection with custom Doctrine 2 hydrator, but I need to inject a service into a custom data type, not into a hydrator.

The solution in the referenced question is relies on duplicating and modifying doctrine source code as Doctrine initializes the classes itself. Hopefully another approach is viable to custom data types?

This is for a Symfony3 application, if there could be some magic to be applied there.

Community
  • 1
  • 1
bblue
  • 545
  • 5
  • 24
  • What makes this hard is how Doctrine instantiates custom data types. The `Type::addType($name, $className)` method for doctrine just wants the class name, not an instance of a class. What you could do is add your custom doctrine type within your bundles extension class, then register an event listener service on on `kernel.request` that has the needed dependencies and set them into your data type by calling `\Doctrine\DBAL\Types::getType($name)->setSomeDependency($dependency);`. Kinda messy though. – ChadSikorra Jul 06 '16 at 19:53
  • 1
    @ChadSikorra That is similar to the approach [here](http://php-and-symfony.matthiasnoback.nl/2012/09/symfony2-mongodb-odm-creating-custom-types-with-dependencies/) that I found just after posting the question, without the event listener. I am experimenting with this now, and it seems promising. Add your comment as an answer and I'll accept it. – bblue Jul 06 '16 at 20:47

1 Answers1

4

Per the comments in the initial question:

What makes this hard is how Doctrine instantiates custom data types. The Type::addType($name, $className) method for doctrine just wants the class name, not an instance of a class. What you could do is add your custom doctrine type within your bundles extension class, then register an event listener service on on kernel.request that has the needed dependencies and set them into your data type by calling \Doctrine\DBAL\Types::getType($name)->setSomeDependency($dependency);. Kinda messy though.

Good find on Matthias' article. The boot() method of the extension class does look like a more natural place to set the dependencies.

ChadSikorra
  • 2,829
  • 2
  • 21
  • 27