我正在编写一个使用一些 Symfony 组件的开源应用程序,并使用 Symfony 控制台组件与 shell 交互。
但是,我需要注入(inject)依赖项(在所有命令中使用),例如 Logger、Config 对象、Yaml 解析器。我通过扩展 Symfony\Component\Console\Command\Command
解决了这个问题类(class)。但这使单元测试变得更加困难并且看起来不正确。
我该如何解决这个问题?
最佳答案
由于 Symfony 4.2 ContainerAwareCommand 已弃用。请改用 DI。
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Doctrine\ORM\EntityManagerInterface;
final class YourCommand extends Command
{
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// YOUR CODE
$this->entityManager->persist($object1);
}
}
关于symfony - 如何将依赖项注入(inject) Symfony 控制台命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7597912/