gpt4 book ai didi

php - 来自 Controller 的控制台/Symfony 调用命令

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:55:39 24 4
gpt4 key购买 nike

当我尝试从 Controller 调用命令时,控制台 出现一些问题。我在 Symfony CookBook 中找到了一种方法: http://symfony.com/doc/current/cookbook/console/command_in_controller.html

好像不行...可能是我忘记了什么!

命令:

namespace AppBundle\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 GreetCommand extends Command
{
protected function configure()
{
$this
->setName('demo:greet')
->setDescription('Greet someone')
->addArgument(
'name',
InputArgument::OPTIONAL,
'Who do you want to greet?'
)
->addOption(
'yell',
null,
InputOption::VALUE_NONE,
'If set, the task will yell in uppercase letters'
)
;
}

protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if ($name) {
$text = 'Hello '.$name;
} else {
$text = 'Hello';
}

if ($input->getOption('yell')) {
$text = strtoupper($text);
}

$output->writeln($text);
}
}

(命令在cmd中运行良好)

Controller :

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;


class MainController extends Controller
{
public function indexAction()
{
$kernel = $this->get('kernel');
$application = new Application($kernel);
$application->setAutoExit(false);

$input = new ArrayInput(array(
'command' => 'demo:greet'
));

$output = new BufferedOutput();
$application->run($input, $output);

$content = $output->fetch();

dump($content);die;
}
}

响应

[Symfony\Component\Console\Exception\CommandNotFoundException] There are no commands defined in the "demo" namespace. 

预先感谢您的帮助。

最佳答案

您使用了错误的应用程序。您应该将 use Symfony\Component\Console\Application; 替换为 use Symfony\Bundle\FrameworkBundle\Console\Application;

关于php - 来自 Controller 的控制台/Symfony 调用命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36748588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com