如何将依赖项注入 Symfony 控制台命令? [英] How can i inject dependencies to Symfony Console commands?

查看:16
本文介绍了如何将依赖项注入 Symfony 控制台命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个开源应用程序,使用一些 Symfony 组件,并使用 Symfony Console 组件与 shell 交互.

I'm writing an open source application uses some Symfony components, and using Symfony Console component for interacting with shell.

但是,我需要注入依赖项(用于所有命令),例如 Logger、Config 对象、Yaml 解析器.我通过扩展 SymfonyComponentConsoleCommandCommand 类解决了这个问题.但这使单元测试变得更加困难并且看起来不正确.

But, i need to inject dependencies (used in all commands) something like Logger, Config object, Yaml parsers.. I solved this problem with extending SymfonyComponentConsoleCommandCommand class. But this makes unit testing harder and not looks correct way.

我该如何解决这个问题?

How can i solve this ?

推荐答案

use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;

ContainerAwareCommand 扩展您的 Command 类并使用 $this->getContainer()->get('my_service_id');

Extends your Command class from ContainerAwareCommand and get the service with $this->getContainer()->get('my_service_id');

这篇关于如何将依赖项注入 Symfony 控制台命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆