如何从控制器内部获取Symfony2中Web目录的服务器路径? [英] How to get the server path to the web directory in Symfony2 from inside the controller?

查看:92
本文介绍了如何从控制器内部获取Symfony2中Web目录的服务器路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题如下:

如何从控制器内部(或出于其他原因,从其他任何地方)获取Symfony2中Web目录的服务器路径

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):

这在有关Doctrine文件处理的食谱文章中建议

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?

在第一个symfony中,一切都很容易,通过调用静态sfConfig :: get()方法,我可以从代码的任何地方获得所需的一切.

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..

推荐答案

由于框架完全独立于webdir,因此在Symfony2中实际上没有直接获取webdir路径的方法.

There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.

您可以在编写内核类的实例上使用getRootDir().如果以后考虑重命名/web目录,则应使其可配置.例如,AsseticBundle在其DI配置中具有这样的选项(请参见此处此处).

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).

这篇关于如何从控制器内部获取Symfony2中Web目录的服务器路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆