官方文檔 :http://symfony.com/doc/current/cookbook/console/console_command.htmlphp
如何建立一個命令;在你的bundle下面建立一個Commmand文件夾 再建立一個 以 Command.php爲後綴的文件(eg:GreetCommand.php)html
###官方例子app
// src/AppBundle/Command/GreetCommand.php 文件位置 namespace AppBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class GreetCommand extends ContainerAwareCommand { protected function configure() { $this ->setName('demo:greet') #命令名稱 ->setDescription('Greet someone')#描述 ->addArgument( #參數 'name', InputArgument::OPTIONAL, 'Who do you want to greet?' ) ->addOption( 'yell', #選項 null, InputOption::VALUE_NONE, 'If set, the task will yell in uppercase letters' ) ; } //執行邏輯 protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); if ($name) { $text = 'Hello '.$name; } else { $text = 'Hello'; } if ($input->getOption('yell')) { $text = strtoupper($text); } $output->writeln($text); } }
執行
php app/console demo:greet Fabie
this
在命令中使用 服務容器 獲取服務spa
protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $logger = $this->getContainer()->get('logger'); //獲取日誌服務 $logger->info('Executing command for '.$name); // ... }
須要注意的是不要去獲取具備必定範圍的容器(request)不然將會報錯;翻譯
####使用翻譯服務容器 protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); $locale = $input->getArgument('locale');日誌
$translator = $this->getContainer()->get('translator'); $translator->setLocale($locale); //必需要設置 if ($name) { $output->writeln( $translator->trans('Hello %name%!', array('%name%' => $name)) ); } else { $output->writeln($translator->trans('Hello!')); } }