symfony2 创建 命令

官方文档 :http://symfony.com/doc/current/cookbook/console/console_command.html

如何创建一个命令;在你的bundle下面创建一个Commmand文件夹
再创建一个 以 Command.php为后缀的文件(eg:GreetCommand.php)

官方例子

// 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

在命令中使用 服务容器 获取服务

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!'));
    }
}

你可能感兴趣的:(命令,console,symfony2)