Get the Symfony project root directory

Published on 2018-10-28 • Modified on 2018-11-06

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. 😉

<?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 Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
trait Snippet6Trait
    public function snippet6(): void
        if (!$this->kernel instanceof KernelInterface) {
            throw new \RuntimeException("Houston, We've Got a Problem. 💥");

        //$rootDir = \dirname($kernel->getRootDir()); // <= Symfony 3.2
        $rootDir = $this->kernel->getProjectDir();    // >= Symfony 3.3, Symfony4

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

        // That's it! 😁

 Run this snippet  More on Stackoverflow