Sortie du snippet Symfony "Récupérer le répertoire racine d'un projet Symfony"

Environnement :

  • Strangebuzz Snippet VM : 6.4.2
  • Symfony : 6.4.3

Sortie du code exécuté :

With the kernel:/var/www-protected/strangebuzz.com
With the container parameter:/var/www-protected/strangebuzz.com
<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpKernel\KernelInterface;

/**
 * %docblock1%
 * %docblock2%
 * %docblock3%
 * %docblock4%.
 *
 * @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! 😁
    }
}