如何在 Symfony 4 控制台命令中获取应用程序根路径

use*_*408 5 php console symfony symfony4

我有一个简单的Symfony 4 Console 应用程序。在execute()方法中,我需要打印应用程序根路径。

$this->getContainer()->get('kernel')->getRootDir()- 不行。
$this->get('kernel')->getRootDir();- 不行。
$this->get('parameter_bag')->get('kernel.project_dir');- 不行。

如何获取应用程序根路径?

Rob*_*ert 7

我建议不要将容器注入命令,而是在服务定义中明确传递参数

源代码/命令

class YourCommand extends Command
{
    private $path; 

    public function __construct(string $path) 
    {
         $this->path = $path;
    }

    public function (InputInterface $input, OutputInterface $output)
    {
       echo $this->path;
    }
}
Run Code Online (Sandbox Code Playgroud)

配置/服务.yaml

services:
    # ...

    App\Command\YourCommand:
        arguments:
            $path: '%kernel.project_dir%'
Run Code Online (Sandbox Code Playgroud)

  • 1. 代码更具可读性,通过查看你的依赖 +- 类做什么 2. 类是可测试的,你可以模拟依赖而不是模拟整个容器 3. 注入容器被认为是不好的做法 4. 你'当容器被编译时,会收到关于缺少依赖项的通知。5. 使用 $container->get('mailer') 时更容易的类型提示 IDE 不知道它是什么,除非你使用 `@var Mailer` 等。还有更多的“for”使用直接依赖 (3认同)