默認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 }