Get the Symfony project root directory

Published on 2018-10-28 • Modified on 2019-12-08

One learn every day! This is so true, in fact I have created this snippet because I didn't knew about the Kernel::getProjectDir() function that was introduced in Symfony 3.3. Before, with Symfony 3.2 and below one had to get the parent directory of the getRootDir() function. So it's easier now! I think I will remember. 😉
[2019-12-08] Added alternative using the kernel.project_dir container parameter.


<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpKernel\KernelInterface;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 *
 * @property KernelInterface $kernel
 */
trait Snippet6Trait
{
    public function snippet6(): void
    {
        // 1. Using the Kernel
        //$rootDir = \dirname($kernel->getRootDir()); // <= Symfony 3.2
        $projectDir = $this->kernel->getProjectDir(); // >= Symfony 3.3
        echo 'With the kernel:'.$projectDir.PHP_EOL;

        // 2. Using the kernel.project_dir parameter
        $projectDirAlt = $this->getParameter('kernel.project_dir');
        echo 'With the container parameter:'.$projectDir.PHP_EOL;

        if ($projectDir !== $projectDirAlt) {
            throw new \RuntimeException('Project directory are not the same! 💥');
        }

        // Get the template content of this snippet
        $twig = file_get_contents($projectDir.'/src/Controller/Snippet/Snippet6Trait.php');

        echo($twig); // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc