默认symfony把每一个Bundle下的Command中的程序注册为命令,若是该程序继承了ContainerAwareCommand类则symfony自动注入服务容器;这样有一些局限性php
*. 你的命令必须放在Command目录下app
*. 没有办法基于你的环境注册服务或利用一些依赖this
*. 在configure()方法中不能访问服务容器(由于setContainer()尚未被调用)spa
*. 你不能使用同一类建立多个命令(根据不一样的配置)code
解决这些问题,你就须要把你的命令注册为一个服务;tag为console.commandsymfony
services: app.command.my_command: class: AppBundle\Command\MyCommand tags: - { name: console.command }
###使用依赖和参数给命令选项设置默认值继承
// src/AppBundle/Command/GreetCommand.php namespace AppBundle\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class GreetCommand extends Command { protected $defaultName; public function __construct($defaultName) { $this->defaultName = $defaultName; parent::__construct(); } protected function configure() { // try to avoid work here (e.g. database query) // this method is *always* called - see warning below $defaultName = $this->defaultName; $this ->setName('demo:greet') ->setDescription('Greet someone') ->addOption( 'name', '-n', InputOption::VALUE_REQUIRED, 'Who do you want to greet?', $defaultName ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getOption('name'); $output->writeln($name); } } #配置注入参数到命令 parameters: command.default_name: Javier services: app.command.my_command: class: AppBundle\Command\MyCommand arguments: ["%command.default_name%"] tags: - { name: console.command }