How to get the `public` dir from symfony controller?

by elisha_langworth , in category: PHP Frameworks , 4 months ago

How to get the `public` dir from symfony controller?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by orpha , 4 months ago

@elisha_langworth 

You can get the public directory path from a Symfony controller using the following steps:

  1. Inject the KernelInterface dependency in your controller constructor or as a method argument.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use SymfonyComponentHttpKernelKernelInterface;

...

private $kernel;

public function __construct(KernelInterface $kernel)
{
    $this->kernel = $kernel;
}


  1. Use the getRootDir() method of the KernelInterface to get the Symfony application root directory.
1
$rootDir = $this->kernel->getRootDir();


  1. Concatenate the public directory path with the root directory path to get the absolute path to the public directory.
1
$publicDir = $rootDir . '/../public';


Now you can use the $publicDir variable to access files in the public directory from your controller. For example, you can create file paths or URLs to assets like CSS, JavaScript, or image files.