close

[Solved] Symfony 4, get the root path of the project from a custom class (not a controller class)

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Symfony 4, get the root path of the project from a custom class (not a controller class) in php. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How Symfony 4, get the root path of the project from a custom class (not a controller class) Error Occurs?

Today I get the following error Symfony 4, get the root path of the project from a custom class (not a controller class) in php.

How To Solve Symfony 4, get the root path of the project from a custom class (not a controller class) Error ?

  1. How To Solve Symfony 4, get the root path of the project from a custom class (not a controller class) Error ?

    To Solve Symfony 4, get the root path of the project from a custom class (not a controller class) Error If your class is extending: Symfony\Bundle\FrameworkBundle\Controller\AbstractController, then you can get the root dir as

  2. Symfony 4, get the root path of the project from a custom class (not a controller class)

    To Solve Symfony 4, get the root path of the project from a custom class (not a controller class) Error If your class is extending: Symfony\Bundle\FrameworkBundle\Controller\AbstractController, then you can get the root dir as

Solution 1


Without Kernel injection

config/services.yaml

services:
    _defaults:
        autowire: true
        autoconfigure: true
        bind:
            $projectDir: '%kernel.project_dir%'

….

class Foo
{
    private $projectDir;

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

Solution 2

If your class is extending: Symfony\Bundle\FrameworkBundle\Controller\AbstractController, then you can get the root dir as

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

or

Inject ContainerBagInterface to your controller

protected $projectRoot;

public function __construct(ContainerBagInterface $containerBag)
{
    $this->projectRoot = $containerBag->get('kernel.project_dir');;
}

or

Even better and the recommended approach

Inject the root_dir to your Foo class. Add the following to your config under services

services:
    foo:
        class:     App\Path\To\Foo
        arguments: ['%kernel.project_dir%']

The container should pass the argument to your class on resolving, the Foo class should look like this

<?php

namespace App\Path\To;

class Foo {

  private $projectDir;

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

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment