How to get project or root dir in symfony 5?

Member

by gilbert , in category: PHP Frameworks , 9 months ago

How to get project or root dir in symfony 5?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 9 months ago

@gilbert 

In Symfony 5, you can get the project or root directory by using the kernel.project_dir parameter. There are several ways to access this parameter.

  1. Controller: In a controller action, you can access the container and get the parameter using the getParameter() method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use SymfonyBundleFrameworkBundleControllerAbstractController;

class MyController extends AbstractController
{
    public function myAction()
    {
        $projectDir = $this->getParameter('kernel.project_dir');
        // ...
    }
}


  1. Service: If you're inside a service, you can inject the kernel.project_dir parameter as a dependency:
1
2
3
4
5
# config/services.yaml
services:
    AppServiceMyService:
        arguments:
            $projectDir: '%kernel.project_dir%'


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// AppServiceMyService.php
namespace AppService;

class MyService
{
    private $projectDir;

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

    // ...
}


  1. Command: If you need to access the project directory in a command, you can get it via the getProjectDir() method:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;

class MyCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $application = $this->getApplication();
        $projectDir = $application->getKernel()->getProjectDir();
        // ...
    }
}


In all the above examples, the $projectDir variable will hold the path to the project or root directory in Symfony 5.