在Symfony2中动态地设置配置中的BASEURL [英] Dynamically setting the BaseUrl within configuration in Symfony2

查看:134
本文介绍了在Symfony2中动态地设置配置中的BASEURL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Symfony2中的配置中,有一个基本URL没有提及,因为没有请求;应用程序可以在任何CLI或Web服务器中运行,因此我们不能依靠请求。不过,我仍然有配置中要求的样式或JavaScript基本URL(如JQueryHelperBundle,在这里你可以设置你的jQuery本地路径 - 为本地URL)。问题是,有没有动态地设置配置基本URL的一种方式,而不必改变它,这样:

I know that within Symfony2's configuration, there is no reference to the base url, as there is no request; the application could either run in cli or within a web server, and therefore we cannot rely on request. But still, I have configuration that asks for stylesheets or javascript base url (such as the JQueryHelperBundle, where you can set your jquery local path - being the local url). The thing is, is there a way to dynamically set a base url for the configuration, without having to change it so that:


  • 的应用程序可以从正在开发的任何目录移动,无论是WWW / myproject的或www /富/ myproject的,而无需更改设置

  • 生产会的工作是相同的,不同之处在于重写与Apache基本URL将被检测(virtualhosting是常见的,那里的baseURL时被映射到Web目录/').

有没有一种方法来获取基础URL信息?将使用 $的区别_ SERVER ['DOCUMENT_ROOT'] 减去内核根目录是检测这种基本的URL的方法?但对虚拟主机的重订基期为URL上的/ web目录是什么?硬编码的基本URL完全夫妇项目到它矗立在发展和移动项目周围将需要改变基本URL每次,这是烦人。

Is there a way to get that base url information? Would using the difference between $_SERVER['DOCUMENT_ROOT'] minus the kernel root dir be a way to detect such base url? But what about virtualhost rebasing the url to / on the web directory? Hardcoding the base url completely couples the project to where it stands in development, and moving project around would require to change the base url everytime, which is annoying.

那么,有没有一种方法,动态检测Symfony2的配置中的基础URL,根据环境,而不依赖于请求?

So, is there a way to dynamically detect the base url within Symfony2's configuration, according to the environment, without depending on the request?

推荐答案

我不得不这样做,在一个服务,让我在自己的服务注入路由器服务,然后:

I had to do that in a service, so I injected the router service in my own service and then:

$baseUrl = $router->getContext()->getHost();

不过,我认为这更多的作为一个黑客工具,Symfony2的框架,一个真正的夹具。例如,在控制器,你可以轻松地生成绝对URL(从symfony的书为例):

But I considered it more as an hack that a real fixture of Symfony2 framework. For instance, in Controller you can generate absolute url easily (example from the symfony book):

$router->generate('blog_show', array('slug' => 'my-blog-post'), true);

和在树枝模板,您有{{URL}}功能

And in the twig template, you have the {{ url }} function

我希望这有助于

这篇关于在Symfony2中动态地设置配置中的BASEURL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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