php 如何在 ZF2 控制器中获取 baseUrl?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12404578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get baseUrl in ZF2 controller?
提问by Hanmant
In my zf2 controller I want to retrieve the application base URL (for example http://domain.com).
在我的 zf2 控制器中,我想检索应用程序基本 URL(例如http://domain.com)。
I tried the following call but it returns an empty string.
我尝试了以下调用,但它返回一个空字符串。
$this->request->getBasePath();
How can I then get the http://domain.compart of URL in my controller?
我怎样才能http://domain.com在我的控制器中获取URL的一部分?
回答by Andris
I know this is not the prettiest way of doing it but, hey, it works:
我知道这不是最漂亮的方法,但是,嘿,它有效:
public function indexAction()
{
$uri = $this->getRequest()->getUri();
$scheme = $uri->getScheme();
$host = $uri->getHost();
$base = sprintf('%s://%s', $scheme, $host);
// $base would be http://domain.com
}
Or if you don't mind shortening everything you could do it in two lines:
或者,如果您不介意缩短您可以在两行中完成的所有内容:
public function indexAction()
{
$uri = $this->getRequest()->getUri();
$base = sprintf('%s://%s', $uri->getScheme(), $uri->getHost());
}
回答by Daniel M
I'm not sure if there's a native way but you can use the Uriinstance from Request.
You can take this snippet as a workaround until you've found a better solution:
我不知道是否有原生的方式,但你可以使用Uri从实例Request。在找到更好的解决方案之前,您可以将此代码段作为解决方法:
$basePath = $this->getRequest()->getBasePath();
$uri = new \Zend\Uri\Uri($this->getRequest()->getUri());
$uri->setPath($basePath);
$uri->setQuery(array());
$uri->setFragment('');
$baseUrl = $uri->getScheme() . '://' . $uri->getHost() . '/' . $uri->getPath();
This works in the controller context. Note that in line 2, the Uri instance from the request is cloned in order not to modify the request's uri instance directly (to avoid side-effects).
这适用于控制器上下文。请注意,在第 2 行中,请求中的 Uri 实例被克隆,以便不直接修改请求的 uri 实例(以避免副作用)。
I'm not happy with this solution but at least, it is one.
我对这个解决方案不满意,但至少,它是一个。
// Edit: Forgot to add the path, fixed!
// 编辑:忘记添加路径,已修复!

