简体   繁体   English

如何在 ZF2 控制器中获取 baseUrl?

[英]How to get baseUrl in ZF2 controller?

In my zf2 controller I want to retrieve the application base URL (for example http://example.com ).在我的 zf2 控制器中,我想检索应用程序的基本 URL(例如http://example.com )。

I tried the following call but it returns an empty string.我尝试了以下调用,但它返回一个空字符串。

$this->request->getBasePath();

How can I then get the http://example.com part of URL in my controller?然后如何在我的控制器中获取 URL 的http://example.com部分?

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://example.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());
}

I'm not sure if there's a native way but you can use the Uri instance from Request .我不确定是否有本地方式,但您可以使用Request中的Uri实例。 You can take this snippet as a workaround until you've found a better solution:您可以将此代码段作为解决方法,直到找到更好的解决方案:

$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! // 编辑:忘记添加路径,已修复!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM