跳到内容

如何从控制器调用命令

编辑此页

Console 组件文档介绍了如何创建控制台命令。本文介绍如何直接从控制器中使用控制台命令。

您可能需要调用某些仅在控制台命令中可用的函数。通常,您应该重构命令并将一些逻辑移动到可以在控制器中重用的服务中。但是,当命令是第三方库的一部分时,您不想修改或复制他们的代码。相反,您可以直接从控制器运行命令。

警告

与直接从控制台调用相比,从控制器调用命令会对性能产生轻微影响,因为请求堆栈开销。

假设你想从你的控制器内部运行 debug:twig 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// src/Controller/DebugTwigController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;

class DebugTwigController extends AbstractController
{
    public function debugTwig(KernelInterface $kernel): Response
    {
        $application = new Application($kernel);
        $application->setAutoExit(false);

        $input = new ArrayInput([
            'command' => 'debug:twig',
            // (optional) define the value of command arguments
            'fooArgument' => 'barValue',
            // (optional) pass options to the command
            '--bar' => 'fooValue',
            // (optional) pass options without value
            '--baz' => true,
        ]);

        // You can use NullOutput() if you don't need the output
        $output = new BufferedOutput();
        $application->run($input, $output);

        // return the output, don't use if you used NullOutput()
        $content = $output->fetch();

        // return new Response(""), if you used NullOutput()
        return new Response($content);
    }
}

显示彩色命令输出

通过告知 BufferedOutput 它通过第二个参数进行装饰,它将返回 Ansi 彩色编码内容。 SensioLabs AnsiToHtml 转换器 可用于将其转换为彩色 HTML。

首先,需要安装包

1
$ composer require sensiolabs/ansi-to-html

现在,在你的控制器中使用它

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// src/Controller/DebugTwigController.php
namespace App\Controller;

use SensioLabs\AnsiConverter\AnsiToHtmlConverter;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Response;
// ...

class DebugTwigController extends AbstractController
{
    public function sendSpool(int $messages = 10): Response
    {
        // ...
        $output = new BufferedOutput(
            OutputInterface::VERBOSITY_NORMAL,
            true // true for decorated
        );
        // ...

        // return the output
        $converter = new AnsiToHtmlConverter();
        $content = $output->fetch();

        return new Response($converter->convert($content));
    }
}

AnsiToHtmlConverter 也可以注册为 Twig 扩展,并支持可选主题。

这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本