如何在Symfony2应用程序中创建控制台命令

时间:2015-06-17 12:56:47

标签: php symfony symfony-2.6 symfony-components symfony-console

我需要为Symfony2应用程序创建一个控制台命令,我读了文档herehere,虽然我不确定应该遵循的是什么。所以这就是我所做的。

  • /src/PDI/PDOneBundle/Console/PDOneSyncCommand.php
  • 下创建一个文件
  • 编写此代码:

    namespace PDI\PDOneBundle\Console\Command;
    
    use Symfony\Component\Console\Command\Command;
    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 PDOneSyncCommand extends Command
    {
        protected function configure()
        {
            $this
                ->setName('pdone:veeva:sync')
                ->setDescription('Some description');
        }
    
        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);
        }
    }
    
    • /bin
    • 下创建一个文件
    • 编写此代码:

      ! / usr / bin / env php

      要求__ DIR __。' / vendor/autoload.php' ;;

      使用PDI \ PDOneBundle \ Console \ Command \ PDOneSyncCommand; 使用Symfony \ Component \ Console \ Application;

      $ application = new Application(); $ application-> add(new PDOneSyncCommand()); $应用 - >运行();

但是当我通过运行php app/console --shell并点击ENTER进入控制台时,我看不到注册的命令,我缺少什么?

注意:比我更有经验的人可以正确格式化第二段代码吗?

更新1

好的,按照建议并以答案为出发点我构建了这段代码:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $container = $this->getContainer();

    $auth_url = $container->get('login_uri')."/services/oauth2/authorize?response_type=code&client_id=".$container->get('client_id')."&redirect_uri=".urlencode($container->get('redirect_uri'));

    $token_url = $container->get('login_uri')."/services/oauth2/token";
    $revoke_url = $container->get('login_uri')."/services/oauth2/revoke";

    $code = $_GET['code'];

    if (!isset($code) || $code == "") {
        die("Error - code parameter missing from request!");
    }

    $params = "code=".$code
        ."&grant_type=".$container->get('grant_type')
        ."&client_id=".$container->get('client_id')
        ."&client_secret=".$container->get('client_secret')
        ."&redirect_uri=".urlencode($container->get('redirect_uri'));

    $curl = curl_init($token_url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ($status != 200) {
        die("Error: call to token URL $token_url failed with status $status, response $json_response, curl_error ".curl_error(
                $curl
            ).", curl_errno ".curl_errno($curl));
    }

    curl_close($curl);

    $response = json_decode($json_response, true);

    $access_token = $response['access_token'];
    $instance_url = $response['instance_url'];

    if (!isset($access_token) || $access_token == "") {
        die("Error - access token missing from response!");
    }

    if (!isset($instance_url) || $instance_url == "") {
        die("Error - instance URL missing from response!");
    }

    $output->writeln('Access Token ' . $access_token);
    $output->writeln('Instance Url ' . $instance_url);
}

但是当我调用任务时,我收到了这个错误:

  

[Symfony的\元器件\ DependencyInjection \异常\ ServiceNotFoundException的]   您已请求不存在的服务" login_uri"。

为什么呢?我无法访问parameter.yml文件上的参数吗?我失败的地方?

2 个答案:

答案 0 :(得分:2)

您正在阅读有关Console Component的文章。这与在捆绑包中注册命令略有不同。

首先,您的类应该位于Namespace Command中,并且必须在classname中包含Command前缀。你大部分都是这样做的。我将向您展示一个示例命令以掌握该想法,以便您可以继续使用它作为基础。

<?php

namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

// I am extending ContainerAwareCommand so that you can have access to $container
// which you can see how it's used in method execute
class HelloCommand extends ContainerAwareCommand {

    // This method is used to register your command name, also the arguments it requires (if needed)
    protected function configure() {
        // We register an optional argument here. So more below:
        $this->setName('hello:world')
            ->addArgument('name', InputArgument::OPTIONAL);
    }

    // This method is called once your command is being called fron console.
    // $input - you can access your arguments passed from terminal (if any are given/required)
    // $output - use that to show some response in terminal
    protected function execute(InputInterface $input, OutputInterface $output) {
        // if you want to access your container, this is how its done
        $container = $this->getContainer();

        $greetLine = $input->getArgument('name') 
            ? sprintf('Hey there %s', $input->getArgument('name')) 
            : 'Hello world called without arguments passed!'
        ;

        $output->writeln($greetLine);
    }

}

现在,运行app/console hello:world'您应该会在终端看到一个简单的Hello world

希望你有这个想法,不要犹豫,问你是否有问题。

修改

在命令中,由于范围,您无法直接访问请求。但是你可以在调用命令时传递参数。在我的例子中,我注册了可选参数,这导致两个不同的输出。

如果您按照此app/console hello:world调用命令,则会获得此输出

  

Hello world在没有参数的情况下调用!

但如果您提供类似此app/console hello:world Demo的名称,则会得到以下结果:

  

嘿,有演示

答案 1 :(得分:1)

按照Artamiel的answer和下面的评论,在这里你需要建立一个作为CRON任务运行的命令(至少,这就是我完成它的方式):< / p>

  • 首先,声明您的SalesforceCommand班级:

    <?php
    class SalesforceCommand extends ContainerAwareCommand
    {
        protected function configure()
        {
            $this
                ->setName('pdone:veeva:sync')
                ->setDescription('Doing some tasks, whatever...');
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {    
            $myService = $this->getContainer()->get('my.service');
    
            $returnValue = $myService->whateverAction();
    
            if($returnValue === true)
                $output->writeln('Return value of my.service is true');
            else
                $output->writeln('An error occured!');
        }
    }
    
  • 然后,在您想要的任何包中创建您的控制器:

        <?php
        namespace My\MyBundle\Service;          
    
        use Symfony\Component\HttpFoundation\RequestStack;
    
        class ServiceController extends Controller
        {
            private $_rs;
    
            public function __construct(RequestStack $rs)
            {
                $this->_rs = $rs;
            }
    
            public function whateverAction()
            {
                $request = $this->_rs->getCurrentRequest();
    
                // do whatever is needed with $request.
    
                return $expectedReturn ? true : false;
            }
        }
    
  • 最后,在app/config/services.yml

    中注册您的控制器即服务
    services:
        my.service:
            class: My\MyBundle\Service\ServiceController
            arguments: ["@request_stack"]
    

(as of Symfony 2.4, instead of injecting the request service, you should inject the request_stack service and access the Request by calling the getCurrentRequest() method)

  • 您最终可以通过将以下内容添加到crontab中来将其作为CRON作业运行(让它每分钟运行一次):

    * * * * * /usr/local/bin/php /path/to/your/project/app/console pdone:veeva:sync 1>>/path/to/your/log/std.log 2>>/path/to/your/log/err.log
    

希望有所帮助!