php - 创建 symfony 命令扩展控制器
问题描述
我正在编写一个 symfony 控制台命令,它可以通过使用“php bin/console app:mycommand”(symfony 文档:https ://symfony.com/doc/current/console.html#creating-a-command )来执行。
在我的 MyCommand 类中,我需要使用 getDoctrine 函数,所以我必须扩展控制器,但我看不到如何做到这一点。有任何想法吗?
目前我在 CLI 上收到以下错误:尝试调用类“App\Command\MyCommand”的名为“getDoctrine”的未定义方法。
<?php
// src/Command/MyCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyCommand extends Command
{
// the name of the command (the part after "bin/console")
protected static $defaultName = 'app:mycommand';
protected function configure()
{
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Not working, producing mentioned error
$em = $this->getDoctrine()->getManager();
}
}
?>
解决方案
该getDoctrine()
方法由 提供ControllerTrait
,而后者又取决于ContainerAwareTrait
容器注入的 。但是,这将提取您在命令中不需要的其他服务和方法,因此建议的方法是只注入您需要的服务,而不是注入整个容器,在这种情况下是ObjectManager
(ObjectManager
是实现的通用接口都由 ORM 和 ODM,如果你同时使用或者你只关心 ORM,你可以使用Doctrine\ORM\EntityManagerInterface
)。
<?php
// src/Command/MyCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\Common\Persistence\ObjectManager;
class MyCommand extends Command
{
// the name of the command (the part after "bin/console")
protected static $defaultName = 'app:mycommand';
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Now you have access to the manager methods in $this->manager
$repository = $this->manager->getRepository(/*...*/);
}
}
推荐阅读
- lisp - ECL:文件系统不接受带有扩展字符的文件名
- r - 团体小提琴情节
- java - 如何以编程方式禁用android中其他应用程序的网络使用?
- php - 如何保护对django网站的恶意攻击
- javascript - React Native upload file using fetch, server $_FILES return object, how to access tmp_name
- php - 类名中的空格是否会导致简单 HTML DOM 出现问题?
- java - 关于java类和构造函数
- python - 输出缺少尾随换行符
- javascript - 比较 2 个对象并将键删除/添加到对象 B
- python - 如何在 asyncio 中复制线程代码?