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

查看:19
本文介绍了如何从控制器内部获取到 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..

推荐答案

实际上没有直接的方法可以在 Symfony2 中获得 webdir 的路径,因为框架完全独立于 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天全站免登陆