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

moh*_*bri 0 symfony symfony-3.4

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

$this->get('kernel')->getProjectDir()
Run Code Online (Sandbox Code Playgroud)

我想在symfony命令(3.4)上获得项目目录,什么是最佳实践?

谢谢

Cer*_*rad 6

可以肯定的是,这个问题已经被问过很多次了,但是我懒得去寻找它。另外,Symfony已从从容器中提取参数/服务转移到注入它们。因此,我不确定以前的答案是否最新。

这很容易。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

# services.yml or services.yaml
services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
        bind:
            $projectDir: '%kernel.project_dir%' # matches on constructor argument name
Run Code Online (Sandbox Code Playgroud)


Man*_*olo 5

您可以注入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;
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)