symfony 4 : How to get “/public” from RootDir

霸气de小男生 提交于 2019-12-05 14:43:36

问题


I have an image under the public folder.
How can I get my image directory in symfony4 ?
In symfony 3, it's equivalent is :

$webPath = $this->get('kernel')->getRootDir() . '/../web/';

回答1:


You can use either

$webPath = $this->get('kernel')->getProjectDir() . '/public/'; 

Or the parameter %kernel.project_dir%

$container->getParameter('kernel.project_dir') . '/public/';



回答2:


It is a bad practice to inject the whole container, just to access parameters, if you are not in a controller. Just auto wire the ParameterBagInterface like this,

protected $parameterBag;

public function __construct(ParameterBagInterface $parameterBag)
{
    $this->parameterBag = $parameterBag;

}

and then access your parameter like this (in this case the project directory),

$this->parameterBag->get('kernel.project_dir');

Hope someone will find this helpful.

Cheers.




回答3:


parameters:
    webDir: '%env(DOCUMENT_ROOT)%'



回答4:


In Controller (also with inheriting AbstractController):

$projectDir = $this->getParameter('kernel.project_dir');


来源:https://stackoverflow.com/questions/48585265/symfony-4-how-to-get-public-from-rootdir

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