Php Symfony2-如何在自定义控制台命令中访问服务?
我是新来的。我已经创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何做到这一点 在控制器中,我将执行以下操作:Php Symfony2-如何在自定义控制台命令中访问服务?,php,symfony,console,command,Php,Symfony,Console,Command,我是新来的。我已经创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何做到这一点 在控制器中,我将执行以下操作: $nodes = $this->getDoctrine() ->getRepository('MyFreelancerPortfolioBundle:TreeNode') ->findAll(); $em = $this->getDoctrine()->getManager(); foreach($nodes as $
$nodes = $this->getDoctrine()
->getRepository('MyFreelancerPortfolioBundle:TreeNode')
->findAll();
$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
$em->remove($node);
}
$em->flush();
通过命令中的execute()函数执行此操作:
Call to undefined method ..... ::getDoctrine();
如何从execute()函数执行此操作?此外,如果有一种更简单的方法来擦除数据,而不是循环遍历并删除数据,请随意提及。为了能够访问您的命令需要扩展的服务容器 请参阅命令文档一章-
自Symfony 3.3(2017年5月)以来,您可以轻松地在命令中使用依赖项注入 只需在您的
服务中使用。yml
:
services:
_defaults:
autowire: true
App\Command\:
resource: ../Command
然后使用通用的构造函数注入,最后,即使是命令
也将具有干净的体系结构:
final class MyCommand extends Command
{
/**
* @var SomeDependency
*/
private $someDependency;
public function __construct(SomeDependency $someDependency)
{
$this->someDependency = $someDependency;
// this is required due to parent constructor, which sets up name
parent::__construct();
}
}
自2017年11月Symfony 3.4以来,这将(或已经,取决于时间读数)成为标准。如何在Symfony\Bundle\FrameworkBundle\Console\Application()中注册这些命令?
final class MyCommand extends Command
{
/**
* @var SomeDependency
*/
private $someDependency;
public function __construct(SomeDependency $someDependency)
{
$this->someDependency = $someDependency;
// this is required due to parent constructor, which sets up name
parent::__construct();
}
}