Oleg Patrushev
Oleg Patrushev

Reputation: 265

How can I get route from url in zf2

I need to make redirect after login in zf2 For example come to login page with url /user/login?redirect=http%3A%2F%site.loc%2Fcategory%test and I need to get route from url maybe some

$router->getRouteFromUri($uri);

Upvotes: 1

Views: 1272

Answers (2)

AlexP
AlexP

Reputation: 9857

The request instance can be used to return the request parameters. This can be fetched from within a controller using any of the following.

$request = $this->getRequest();
$request = $this->getEvent()->getRequest();
$request = $this->getServiceLocator()->get('request');

However, there is already the Zend\Mvc\Controller\Plugin\Params that can be used for route or any other request parameters, should you need to access it from the controller.

$redirect = $this->params('redirect', false); 
// or
$redirect = $this->params()->fromQuery('redirect', false);

If you need to generate the URL you can use the URL plugin Zend\Mvc\Controller\Plugin\Url.

$this->url()->fromRoute(
    $nameOfRoute, // use null for last matched route
    $arrayOfRouteParams,
    $booleanShouldReuseMatchedParams,
    array(
        'query' => array('redirect' => $redirctUrl)
    )
);

Where the above is simply a convenience class for manually assembling the URL directly with the router.

Upvotes: 1

Oleg Patrushev
Oleg Patrushev

Reputation: 265

So as @cptnk said the best way is

        $request = new Request();
        $request->setMethod(Request::METHOD_GET);
        $request->setUri($uri);

        $this->router->match($request);

which returns route with params

Upvotes: 3

Related Questions