The question is as follows:
How can I get the server path to the web directory in Symfony2 from inside the controller (or from anywhere else for that reason)
What I've already found (also, by searching here):
This is advised in the cookbook article on Doctrine file handling
$path = __DIR__ . '/../../../../web';
Found by searching around, only usable from inside the controller (or service with kernel injected):
$path = $this->get('kernel')->getRootDir() . '/../web';
So, is there absolutely no way to get at least that 'web' part of the path? What if I, for example, decided to rename it or move or something?
Everything was easy in the first symfony, when I could get like everything I needed from anywhere in the code by calling the static sfConfig::get() method..
There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.
You can use getRootDir()
on instance of kernel class, just as you write. If you consider renaming /web
dir in future, you should make it configurable. For example AsseticBundle has such an option in its DI configuration (see here and here).
To access the root directory from outside the controller you can simply inject %kernel.root_dir%
as an argument in your services configuration.
service_name:
class: Namespace\Bundle\etc
arguments: ['%kernel.root_dir%']
Then you can get the web root in the class constructor:
public function __construct($rootDir)
{
$this->webRoot = realpath($rootDir . '/../web');
}
You also can get it from any ContainerAware (f.i. Controller) class from the request service:
If you are using apache as a webserver (I suppose for other
webservers the solution would be similar) and are using
virtualhosting (your urls look like this - localhost/app.php
then you can use:
$container->get('request')->server->get('DOCUMENT_ROOT');
// in controller:
$this->getRequest()->server->get('DOCUMENT_ROOT');
Else (your urls look like this - localhost/path/to/Symfony/web/app.php
:
$container->get('request')->getBasePath();
// in controller:
$this->getRequest()->getBasePath();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With