How to get the root dir of the Symfony2 application?

ぃ、小莉子 提交于 2019-12-03 00:28:57

问题


What is the best way to get the root app directory from inside the controller? Is it possible to get it outside of the controller?

Now I get it by passing it (from parameters) to the service as an argument, like this:

services:

    sr_processor:
        class: Pro\Processor
        arguments: [%kernel.root_dir%]

Is there a better, simpler way to get this information in Symfony2?


回答1:


UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...




回答2:


In Symfony 3.3 you can use

$projectRoot = $this->get('kernel')->getProjectDir();

to get the web/project root.




回答3:


If you are using this path to access parts of the projects which are not code (for example an upload directory, or a SQLite database) then it might be better to turn the path into a parameter, like this:

parameters:
    database_path: '%kernel.root_dir%/../var/sqlite3.db'

This parameter can be injected everywhere you need it, so you don't have to mess around with paths in your code any more. Also, the parameter can be overridden at deployment time. Finally, every maintaining programmer will have a better idea what you are using it for.

Update: Fixed kernel.root_dir constant usage.




回答4:


You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;



回答5:


Since Symfony 3.3 you can use binding, like

services:
_defaults:
    autowire: true      
    autoconfigure: true
    bind:
        $kernelProjectDir: '%kernel.project_dir%'

After that you can use parameter $kernelProjectDir in any controller. Just like

class SomeController
{
    public function someAction(...., $kernelProjectDir)
    {
          .....


来源:https://stackoverflow.com/questions/9215753/how-to-get-the-root-dir-of-the-symfony2-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!