zend framework 2 base path access in controller

2019-02-25 04:18发布

问题:

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');

回答1:

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


回答2:

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


回答3:

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/