在Symfony中默认机制之外的机制中启用依赖项注入



我的Symfony应用程序中有一种机制,需要基于默认服务容器启用依赖项注入。我在HttpKernel中找到了代码,在这里,依赖注入是通过控制器机制管理的(在Sourcegraph上浏览(。

然而,我不确定如何实例化ArgumentResolver以用于此目的。

以下是我迄今为止所尝试的:

class DataSourceController
{
public function queryDatasource(string $hash, Request $request, ArgumentResolverInterface $argument_resolver)
{
// Logic to construct the $datasource variable
$arguments = $argument_resolver->getArguments($request, [$datasource, 'query']);
$data = $datasource->query(...$arguments);
return new JsonResponse($data);
}
}

然而,ArgumentResolverInterface似乎无法自动连接,我不确定该如何处理。那么,我如何实例化ArgumentResolverInterface的子类,或者我应该使用什么其他机制来实现应用程序任意组件中的依赖注入呢?

在对Symfony的来源进行了更多的研究和扫描后,我能够找到一个适合我需求的解决方案:我手动创建ArgumentResolver的实例并使用它。

注意我的用例需要解析一个不是服务的对象,因此它不能像任何其他服务一样通过依赖注入机制来解析。我在回答中包括了这一点,因为它可能对其他人有用:

$resolvers = [];
array_push($resolvers, ...ArgumentResolver::getDefaultArgumentValueResolvers());
array_push($resolvers, new class implements ArgumentValueResolverInterface {
// implement the interface to resolve an argument with a specific type/name
});
$argument_resolver = new ArgumentResolver(new ArgumentMetadataFactory(), $resolvers);
// to use it:
$arguments = $argument_resolver->getArguments($request, [$datasource, 'query']);
$datasource->query(...$arguments);

我希望这对其他人有用。


我不能证明这是解决方案或最佳解决方案,但它似乎适用于我的用例。我欢迎其他人评论/回答,这样我们就可以一起改进解决方案

最新更新