我想在登录后后台运行一个自定义的symfony2控制台命令。我制作了一个监听器,并尝试使用该进程在后台运行命令,但函数运行不好。这是我的代码
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;
}
}
我的代码有问题吗?谢谢你的帮助。
任何需要从匿名函数内部访问的变量都必须使用use
语句。此外,由于范围的原因,这可能会发生冲突。
$that = $this;
$process->start(function ($type, $buffer) use ($that) {
$command = $that->RecommendJobService;
$input = new ArgvInput();
$output = new ConsoleOutput();
$command->execute($input, $output);
echo "1";
});
此外,您还可以使用匿名函数,并在start()方法之外对其进行测试,如下所示。
$closure = function ($type, $buffer) use ($that) {
$command = $that->RecommendJobService;
$input = new ArgvInput();
$output = new ConsoleOutput();
$command->execute($input, $output);
echo "1";
};
$closure();
然后你可以在那里进行一些调试,看看它是否能运行。我不确定echo是否是处理控制台的好方法。我建议使用Monolog或$output->writeln($text);
命令。