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

Environnement :

  • Strangebuzz Snippet VM : 2.8.0
  • Symfony : 5.3.5

Sortie du code exécuté :

With the kernel:/var/www-deploy/strangebuzz.com/releases/20210801104121
With the container parameter:/var/www-deploy/strangebuzz.com/releases/20210801104121
<?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! 😁
    }
}