在命令 symfony 3.4 上获取项目目录

Get project directory on command symfony 3.4

使用symfony 3.4 在控制器中,我可以使用这种方法获取项目目录:

$this->get('kernel')->getProjectDir()

我想通过命令 symfony (3.4) 获取项目目录,最佳做法是什么?

谢谢

嗯,我会说,直接注入 %kernel.project_dir%%kernel.root_dir% 参数在你的指挥下。无需使您的命令依赖于内核服务。

顺便说一句,您还可以让您的命令扩展 Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand,这是一个抽象 class。因此,您只需调用 getContainer 方法即可在命令中访问容器。

但是,实际上我不会建议你这样做。最好利用 autowiring 或以 "yaml" 方式配置您的服务。

很确定这个问题已经被问过很多次了,但我懒得去搜索了。另外,Symfony 已经从从容器中拉取 parameters/services 转变为注入它们。所以我不确定以前的答案是否是最新的。

这很容易。

namespace AppBundle\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Command\Command;

class ProjectDirCommand extends Command
{
    protected static $defaultName = 'app:project-dir';

    private $projectDir;

    public function __construct($projectDir)
    {
        $this->projectDir = $projectDir;
        parent::__construct();
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Project Dir ' . $this->projectDir);
    }
}

因为你的项目目录是一个字符串,自动装配将不知道要注入什么值。您可以将命令明确定义为服务并手动注入值,也可以使用绑定功能:

# services.yml or services.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
        bind:
            $projectDir: '%kernel.project_dir%' # matches on constructor argument name

您可以将KernelInterface注入到命令中,只需将其添加到构造函数参数中,然后使用$kernel->getProjectDir():

获取项目目录
<?php

namespace App\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class FooCommand extends Command
{
    protected $projectDir;

    public function __construct(KernelInterface $kernel)
    {
        parent::__construct();
        $this->projectDir = $kernel->getProjectDir();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        echo "This is the project directory: " . $this->projectDir;
        //...
    }
}