Symfony2 Console Component开发

      在Symfony2中可以用命令行调用并运行你的程序,这在需要设置定时任务时十分方便。我们只需把要执行的逻辑操作按照框架命令行接口的格式写好,然后通过终端进入项目根目录,运行命令即可。

     一、在Bundle下新建一个文件夹Command用来存放我们要编写的命令 runCommand.php

<?php

/**
* Description of runCommand
*
* @author dluf
*/
namespace Acme\DemoBundle\Command;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Console\Command\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 runCommand extends ContainerAwareCommand{

protected function configure()
{
$this
->setName('Dluf:dluf')
->setDescription('Call Dluf')
->addArgument('name', InputArgument::OPTIONAL, 'Check Dluf')
->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');
$show = $name.$this->viewshow();
print_r("-------------------".$show."------------------------------");
}

private function viewshow(){
return date('Y-m-d H:i:s',time())."开始执行命令";
}

}

?>

二、在bundle下编写个application调用该命令

#!/usr/bin/env php
# app/console
<?php
use Acme\DemoBundle\Command\runCommand;
use Symfony\Component\Console\Application;

$application = new Application();
$application->add(new runCommand);
$application->run();

?>

三、用终端调用该命令,如图所示:命令被执行,打印出我们定义的字符串

原文地址:https://www.cnblogs.com/dluf/p/2864062.html