我有一个命令,它执行一些依赖于参数传递的实体的动作。
checkAlertCommand.php:
<?php
namespace MDB\PlatformBundle\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 checkAlertCommand extends Command {
protected function configure() {
$this
->setName('platform:checkAlert')
->setDescription('Check the alert in in function of the current advert')
->addArgument(
'postedAdvert'
);
}
protected function execute(InputInterface $input, OutputInterface $output) {
$postedAdvert = $input->getArgument('postedAdvert');
$output->writeln($postedAdvert->getTitre());
}
}
?>
所以我的问题是:
感谢。
答案 0 :(得分:0)
您无法将实体直接传递给控制台命令。而不是你应该将实体的“id”作为参数传递,然后使用存储库并通过其id来获取所需的实体。
<?php
namespace MDB\PlatformBundle\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 checkAlertCommand extends ContainerAwareCommand {
protected function configure() {
$this
->setName('platform:checkAlert')
->setDescription('Check the alert in in function of the current advert')
->addArgument(
'postedAdvertId'
);
}
protected function execute(InputInterface $input, OutputInterface $output) {
$postedAdvertId = $input->getArgument('postedAdvertId');
$em = $this->getContainer()->get('doctrine')->getManager();
$repo = $em->getRepository('MDBPlatformBundle:PostedAdvert');
$postedAdvert = $repo->find($postedAdvertId);
$output->writeln($postedAdvert->getTitre());
}
}
?>
您应该使用Process组件在控制器内运行命令。
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use MDB\PlatformBundle\Command\checkAlertCommand;
class MyController extends Controller
{
public function indexAction()
{
// get post $postedAdvertId here
....
$command = new checkAlertCommand();
$command->setContainer($this->container);
$input = new ArrayInput(array('postedAdvertId' => $postedAdvertId));
$output = new NullOutput();
$result = $command->run($input, $output);
...
}
}
更新:回答您的问题
我不确定你究竟是什么意思“异步”,但是给定的例子以同步的方式执行命令,这意味着控制器将等到命令完成后才会进入下一个操作。但是,如果您需要以异步(后台)方式运行它,则应使用Process组件http://symfony.com/doc/current/components/process.html