简体   繁体   English

控制器中的 symfony 3 控制台命令列表

[英]symfony 3 console command list in controller

As I am not sure how to describe it, I didn't found any results in google or stack.由于我不确定如何描述它,我没有在 google 或 stack 中找到任何结果。

I would like to list all available console commands (which are callable by using the bin/console) with a Controller-Action so that I can forward a list of all commands to twig.我想用 Controller-Action 列出所有可用的控制台命令(可以使用 bin/console 调用),以便我可以将所有命令的列表转发给 twig。

How can I realize this ?我怎么能意识到这一点?

Interesting question.有趣的问题。 You can of course just run the console command itself and capture the list of commands.您当然可以只运行控制台命令本身并捕获命令列表。 Might actually be the best way.实际上可能是最好的方法。

However, there is a service called console.command_loader which has a method called getNames which does indeed return a list of command names.但是,有一个名为console.command_loader的服务,它有一个名为 getNames 的方法,它确实返回了一个命令名称列表。 It implements CommandLoaderInterface.它实现了 CommandLoaderInterface。

Originally I tried to create an alias so it could be injected into an action method:最初我尝试创建一个别名,以便可以将其注入到操作方法中:

services:
   Symfony\Component\Console\CommandLoader\CommandLoaderInterface: 
       alias: console.command_loader

But I kept getting console.command_loader not found which was puzzling since debug:container shows it.但是我不断得到 console.command_loader not found ,这令人费解,因为 debug:container 显示了它。 The service was tagged with container.no_preload which might have something to do with it.该服务被标记为可能与它有关的container.no_preload Not sure.没有把握。

So I went and just defined the controller service:所以我去定义了控制器服务:

services:
    App\Controller\CommandController:
        tags:
            - 'controller.service_arguments'
        arguments:
            - '@console.command_loader'

And somewhat to my surprise it worked.令我惊讶的是,它奏效了。

class CommandController extends AbstractController
{
    public function __construct(private CommandLoaderInterface $cl)
    {
    }
   
    #[Route('/commands', name: 'app_commands')]
    public function commands(): Response
    {
        $names = $this->cl->getNames();
        dump($names);

        // I happen to have a command called app:init
        $initCommand = $this->cl->get('app:init');
        dump($initCommand->getDescription());

        //return $this->render('default/index.html.twig', [
        //    'controller_name' => 'DefaultController ' . 'Commands',
        //]);
    }
}

This was all done in Symfony 6. Did not happen to have a Symfony 3 app handy.这一切都是在 Symfony 6 中完成的。碰巧手边没有一个 Symfony 3 应用程序。 Your first step would be to confirm that Symfony 3 also has the service with bin/console debug:container console.command_loader .你的第一步是确认 Symfony 3 也有bin/console debug:container console.command_loader的服务。 If it does not have such a service then poke around a bit and see if it has something similar.如果它没有这样的服务,那就四处看看,看看它是否有类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM