从控制台运行路由方法

问题描述 投票:0回答:2

我希望能够从 URL 和控制台运行控制器的方法。我怎样才能做到这一点?我的意思是,在某个控制器中有一个方法:

/**
 * @Route("/fooBar", name="fooBar")
 */
public function actionFooBar() {
    $this -> get('file') -> saveSomethingToSomeFile();
    return 'a';
}

我希望能够通过

http://domain.com/fooBar
php app/console fooBar
或类似的方式打开它。

控制台无法工作。我该如何解决这个问题?

php symfony
2个回答
2
投票

你想要的是(我认为)技术上可行,但不是好的实践。

您应该将控制器方法中的代码移动到服务中,然后您可以从命令和控制器运行相同的代码。


-1
投票

您需要构建一个命令:

<?php

namespace Application\CommandBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManager;

/**
 * Class testCommand
 * @package Application\CommandBundle\Command
 */
class TestCommand extends ContainerAwareCommand
{

/**
 * Configuration of the command
 */
protected function configure()
{
    $this
        ->setName('command:do:something')
        ->setDescription('This command does something');
}

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

}

/**
 * @param InputInterface  $input  An InputInterface instance
 * @param OutputInterface $output An OutputInterface instance
 *
 * @return null|int null or 0 if everything went fine, or an error code
 */
protected function execute(InputInterface $inputInterface, OutputInterface $outputInterface)
{
    $outputInterface->writeln(
        'This command does something <info>' . $inputInterface->getOption('env') . '</info> environment'
    );

    $this->getContainer()->get('application_command.test')->doSomething();

    $outputInterface->writeln('Done');
}

}

更多详细信息:https://codingformat.com

© www.soinside.com 2019 - 2024. All rights reserved.