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 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 (typehint with "KernelInterface")
        // $projectDir = \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 directories 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  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  Random snippet

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @see Snippet6Trait
 */
final class Snippet6Test extends KernelTestCase
{
    private string $projectDir;

    protected function setUp(): void
    {
        $this->projectDir = self::getContainer()->getParameter('kernel.project_dir');
    }

    /**
     * @see Snippet6Trait::snippet6
     */
    public function testSnippet6(): void
    {
        self::assertSame(self::$kernel->getProjectDir(), $this->projectDir);
    }
}