Symfony provides various features and improvements to streamline the development process. One common requirement during Symfony development is the need to dynamically access the project directory within the code. It can be useful for locating files, configuring services, or for other tasks. This tutorial demonstrates how to get project directory in Symfony 7.
Controller - Method 1
When a controller extends the AbstractController class, we can utilize the getParameter method to retrieve the kernel.project_dir parameter directly from the container.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController extends AbstractController
{
#[Route('/')]
public function index(): Response
{
$dir = $this->getParameter('kernel.project_dir');
return new Response($dir);
}
}
Controller - Method 2
In cases where the controller doesn't extend the base controller, the Autowire attribute can be employed to inject the value of the kernel.project_dir parameter into the constructor property.
src/Controller/TestController.php
<?php
namespace App\Controller;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
public function __construct(#[Autowire('%kernel.project_dir%')] private string $dir)
{
}
#[Route('/')]
public function index(): Response
{
return new Response($this->dir);
}
}
Service
To obtain the project directory within a service, we can inject the value of the kernel.project_dir parameter into the constructor property by using the Autowire attribute.
src/Service/TestService.php
<?php
namespace App\Service;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class TestService
{
public function __construct(#[Autowire('%kernel.project_dir%')] private string $dir)
{
}
}
Leave a Comment
Cancel reply