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

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

问题描述

我在写一个开源应用程序使用一些Symfony组件,并使用Symfony控制台组件与shell进行交互。

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

但是,我需要注入依赖项(用于所有命令)像Logger,Config对象,Yaml解析器..我解决了这个问题与扩展 Symfony\Component\Console\Command\Command 类。但这使得单元测试更难,看起来不正确的方式。

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

如何解决这个问题?

推荐答案

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

ContainerAwareCommand 扩展 Command 获取服务 $ this-> getContainer() - > get('my_service_id');

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

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