Symfony2 - How to access the service in a custom console command?(Symfony2 - 如何在自定义控制台命令中访问服务?)
问题描述
我是 Symfony 的新手.我创建了一个自定义命令,其唯一目的是从系统中擦除演示数据,但我不知道如何执行此操作.
I am new to Symfony. I have created a custom command which sole purpose is to wipe demo data from the system, but I do not know how to do this.
在控制器中我会这样做:
In the controller I would do:
$nodes = $this->getDoctrine()
->getRepository('MyFreelancerPortfolioBundle:TreeNode')
->findAll();
$em = $this->getDoctrine()->getManager();
foreach($nodes as $node)
{
$em->remove($node);
}
$em->flush();
从我得到的命令中的 execute() 函数执行此操作:
Doing this from the execute() function in the command I get:
Call to undefined method ..... ::getDoctrine();
如何通过 execute() 函数执行此操作?此外,如果有更简单的方法来擦除数据而不是循环遍历它们并删除它们,请随时提及.
How would I do this from the execute() function? Also, if there is an easier way to wipe the data other than to loop through them and remove them, feel free to mention it.
推荐答案
为了能够访问服务容器,您的命令需要扩展 SymfonyBundleFrameworkBundleCommandContainerAwareCommand.
In order to be able to access the service container your command needs to extend SymfonyBundleFrameworkBundleCommandContainerAwareCommand.
参见命令文档章节 - 从容器中获取服务.
See the Command documentation chapter - Getting Services from the Container.
use SymfonyBundleFrameworkBundleCommandContainerAwareCommand;
// ... other use statements
class MyCommand extends ContainerAwareCommand
{
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->getContainer()->get('doctrine')->getEntityManager();
// ...
这篇关于Symfony2 - 如何在自定义控制台命令中访问服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony2 - 如何在自定义控制台命令中访问服务?
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
