Dilip Prajapati
Dilip Prajapati

Reputation: 71

zend framework 2 base path access in controller

How can i call basePath helper in controller in ZF 2. I have to redirect to a particular url in which i need base path. return $this->redirect()->toUrl($basePath.'/application/rent/search');

Upvotes: 4

Views: 10146

Answers (3)

Isaac Limón
Isaac Limón

Reputation: 2058

try

class XxxController extends AbstractActionController
{

...

public function basePath()
{
    $basePath = $this->serviceLocator
        ->get('viewhelpermanager')
        ->get('basePath');
    return $basePath();
}

in

OR

public function algoAction()
{
    echo $this->getRequest()->getBaseUrl();
}

http://project.com/profile

returns ""

http://localhost/~limonazzo/public/profile

returns /~limonazzo/public/

Upvotes: 1

aimfeld
aimfeld

Reputation: 3161

Here's an easy method to make all view helpers available from within the controllers. So you should be able to use the following:

public function someAction()
{
    $renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
    $url = $renderer->basePath('/application/rent/search');
    $redirect = $this->plugin('redirect');
    return $redirect->toUrl($url);
}

Upvotes: 7

aimfeld
aimfeld

Reputation: 3161

The full base url (http://...) can be determined from within the controller as follows:

$event = $this->getEvent();
$request = $event->getRequest();
$router = $event->getRouter();
$uri = $router->getRequestUri();
$baseUrl = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), $request->getBaseUrl());

Upvotes: 3

Related Questions