具有自定义Doctrine 2数据类型的依赖项注入

问题描述:

我遇到的问题与使用自定义Doctrine 2水化器进行依赖注入,但是我需要将服务注入自定义的数据类型中,而不是注入到水化器中.

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.

所引用问题的解决方案依赖于复制和修改学说的源代码,而Doctrine会初始化类本身.希望另一种方法对自定义数据类型可行吗?

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?

这是针对Symfony3应用程序的,如果可以在其中应用一些魔术的话.

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

根据最初问题中的评论:

Per the comments in the initial question:

使这一点变得困难的是Doctrine如何实例化自定义数据类型.用于主义的 Type :: addType($ name,$ className)方法只需要类名,而不是类的实例.您可以做的是在捆绑扩展类中添加自定义类型,然后在具有所需依赖项的 kernel.request 上注册事件侦听器服务,并通过调用 \ Doctrine \ DBAL \ Types :: getType($ name)-> setSomeDependency($ dependency); .虽然有点凌乱.

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.

在Matthias的文章中找到了很好的发现.扩展类的 boot()方法看起来确实是设置依赖项的更自然的地方.

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