How to get baseUrl in ZF2 controller?

*爱你&永不变心* 提交于 2019-12-03 08:53:59

问题


In my zf2 controller I want to retrieve the application base URL (for example 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.com part of URL in my controller?


回答1:


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());
}



回答2:


I'm not sure if there's a native way but you can use the Uri instance from Request. 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).

I'm not happy with this solution but at least, it is one.

// Edit: Forgot to add the path, fixed!



来源:https://stackoverflow.com/questions/12404578/how-to-get-baseurl-in-zf2-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!