Symfony 4, how get the root path directory (or /src path) properly from a Service Class ? ( error : 'Call to a member function get() on null')

Symfony 4, how get the root path directory (or /src path) properly from a Service Class ? ( error : 'Call to a member function get() on null')

在 Symfony 4 中,我可以通过以下方式从控制器获取项目的根路径:

// From a Controller Class, in the src/Controller dir

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// ...
Class myController extends Controller{
// ...
// in a public method
$rootDir = $this->get('kernel')->getRootDir();

但是如何从服务中获取根路径 Class? 我试过这种(丑陋的)方式

// From a Service Class, in the src/Service dir

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// ...
Class myService extends Controller{
// ...
// in a public method
$rootDir = $this->get('kernel')->getRootDir();

但是当我这样做时,出现错误:

"Call to a member function get() on null"

为什么这个解决方案不起作用?

Symfony 提供了一个参数kernel.project_dir,可以在服务容器内部使用,你可以注入服务或者从容器中获取(在控制器内部):

$this->getParameter('kernel.project_dir');

在服务中,您只需将其注入构造函数即可:

class MyService
{
    private $projectDir;

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

在您的配置中,您可能必须确保正确传递字符串,方法是直接为此特定服务进行设置:

# config/services.yaml

...

services:

    ...

    App\MyService:
        arguments:
            $projectDir: '%kernel.project_dir%'

或者您可以将此参数绑定到变量名,以便配置自动识别它:

# config/services.yaml

...

services:
    _defaults:
        ...
        bind:
            $projectDir: '%kernel.project_dir%'

然后所有具有参数 $projectDir 的服务(在该配置文件中注册)将从该参数获取值。

我的方法是一样的,但是你可以在构造函数中注入ParameterBaginterface,这样你就可以访问所有的参数。

有了这个,您不必定义服务,因为自动装配让您的生活更轻松。

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class MyService
{
    private $parmeterBag;

    public function __construct(ParameterBagInterface $parameterBag)
    {
        $this->parameterBag= $parameterBag;
    }
}

现在您可以通过 $this->parameterBag->get('your_parameter');

访问您的参数