dpbz14739 2013-08-07 14:10
浏览 128
已采纳

登录Symfony2后运行控制台命令后台

I want to run a custom symfony2 console command background after login. I make a listener and try to use the process to run the command at background but the function not work well. Here is my code

class LoginListener
{
    protected $doctrine;
    private $RecommendJobService;
    public function __construct(Doctrine $doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function onLogin(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();

        if($user)
        {
        $process = new Process('ls -lsa');
        $process->start(function ($type, $buffer) {
                $command = $this->RecommendJobService;
                $input = new ArgvInput();
                $output = new ConsoleOutput();
                $command->execute($input, $output);
                echo "1";

        });
        }
    }
    public function setRecommendJobService($RecommendJobService) {
      $this->RecommendJobService = $RecommendJobService;
    }
}

Is there something wrong with my code? Thx for helping.

  • 写回答

1条回答 默认 最新

  • douxuanjie2692 2013-08-07 17:22
    关注

    Any variables that you need to access from inside your anonymous function you have to use a use statement. Further $this could conflict due to scope.

    $that = $this;
    $process->start(function ($type, $buffer) use ($that) {
        $command = $that->RecommendJobService;
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        $command->execute($input, $output);
        echo "1";
    });
    

    Also you can take your anonymous function and test it outside of the start() method like this.

    $closure = function ($type, $buffer) use ($that) {
        $command = $that->RecommendJobService;
        $input = new ArgvInput();
        $output = new ConsoleOutput();
        $command->execute($input, $output);
        echo "1";
    };
    $closure();
    

    Then you can put some debugging in there and see if it runs. I'm not sure if echo is a good way to deal with the console. I would recommend Monolog or the $output->writeln($text); command.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化