【问题标题】:Symfony2 command within an asynchronous subprocess异步子进程中的 Symfony2 命令
【发布时间】:2014-07-16 06:50:48
【问题描述】:

我是 Symfony2 的新手,在尝试像这样运行异步命令时被阻止:

class MyCommand extends ContainerAwareCommand{

protected function configure()
{
    $this
        ->setName('my:command')
        ->setDescription('My command')
        ->addArgument(
            'country',
            InputArgument::REQUIRED,
            'Which country?'
        )
    ;
}

protected function execute(InputInterface $input, OutputInterface $output)
{

    $country = $input->getArgument('country');


    // Obtain the doctrine manager
    $dm = $this->getContainer()->get('doctrine_mongodb.odm.document_manager');

   $users = $dm->getRepository('MyBundle:User')
        ->findBy( array('country'=>$country));
}}

当我从命令行调用它时效果很好:

php app/console my:command uk

但是当我将它称为 Symfony2 进程时它不起作用:

 $process = new Process("php ../app/console my:command $country");
 $process->start();

我收到一个数据库错误:“[MongoWriteConcernException] 127.0.0.1:27017: not master

我认为这意味着该进程没有获取我的数据库配置...

我只想运行一个异步进程,还有其他方法吗?

也许是一种调用应用程序命令的方式,不需要答案就可以继续运行?

也许我需要使用注射?

PS:我当前的命令只是一个测试,最后它应该是一个“昂贵”的操作......

【问题讨论】:

  • 好吧,我自己找到了解决方案。实际上这是一个愚蠢的问题......我已将环境参数(--env=)添加到进程中,一切都像一个魅力:$process = new Process("php ../app/console my:command $country --env=test");

标签: php mongodb symfony asynchronous process


【解决方案1】:

嗯,我知道发生了什么事......

我使用多种环境:DEV、TEST 和 PROD。

而且我还使用不同的服务器。

所以DEV环境是我自己的机器,配置了简单的mongodb。 但是 TEST 环境在具有 副本集 配置的其他服务器上...

现在错误得到充分理解:"[MongoWriteConcernException] 127.0.0.1:27017: not master"

为了解决这个问题,我刚刚在进程中添加了环境参数 (--env=),一切都很顺利:

$process = new Process("php ../app/console my:command $country --env=test");

实际上,为了获得正确的环境,我使用了这个:

$this->get('kernel')->getEnvironment();

让我的代码如下:

$process = new Process("php ../app/console my:command $country --env=".$this->get('kernel')->getEnvironment());

也许不是一个漂亮的方法,但它对我有用:)

【讨论】:

  • 您还应该使用%kernel.root_dir% 容器参数来创建app/console 的路径
【解决方案2】:

免责声明:这对于您正在尝试做的事情可能有点矫枉过正:)

我会选择相反的方式:pthreads

首先,对 StackOverflow 的快速检查向我展示了一个使用 pthreads 的非常好的示例:Multi-threading is possible in php

然后,知道您可以从另一个命令调用您的命令:

http://www.craftitonline.com/2011/06/calling-commands-within-commands-in-symfony2/

... 让你拼凑所有的部分。这有点复杂,但它可以完成工作。

【讨论】:

  • 感谢您的回答@jperovic。是的,就像你说的,我正在寻找更简单的东西;)
  • 啊,我刚刚阅读了您对原始问题的评论。很高兴您解决了问题。如果这不是问题,请自己添加答案 - 我相信迟早会有人发现它有用......;)
【解决方案3】:

如果你想在 Symfony2/3 中完全异步地执行你的代码,可以使用 AsyncServiceCallBundle

你应该这样称呼它:

$this->get('krlove.async')->call('your_service_id', 'method_name', [$arg1, $arg2]);

它在内部使用this 方法在后台运行您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 2014-06-13
    • 2011-02-03
    • 1970-01-01
    • 2014-12-12
    • 2010-09-14
    • 2011-01-23
    • 2015-08-24
    相关资源
    最近更新 更多