I'm using Zend Framework 2, this is my code:
$prevsingletrackurl = $this->getRequest()->getHeader('Referer')->getUri();
From this code which is defined in a controller's method I'm getting previous URL, now what I need to know some information of this from this, it contains which route, controller, method for my own requirement.
You can use the route stack itself to try to match it. It will return you a RouteMatch if the request object matched:
use Zend\Mvc\Router\RouteMatch;
$referer = $this->getRequest()->getHeader('Referer')->getUri();
$request = clone $this->getRequest();
$request->setUri($referer);
$match = $routeStack->match($request);
if ($match instanceof RouteMatch) {
$route = $match->getMatchedRouteName();
}
You can access the route stack ("router") from the service locator; in the root service locator, it is registered as 'Router'. You can inject the route stack in your factory. For instance in a Controller:
use MyModule\Controller\MyController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $sl)
{
$router = $sl->getServiceLocator()->get('Router');
$controller = new MyController($router);
return $controller;
}
}
Use it in your controller as this:
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\Router\Http\TreeRouteStack;
class MyController extends AbstractActionController
{
protected $router;
public function __construct(TreeRouteStack $router)
{
$this->router = $router;
}
protected function getRouter()
{
return $this->router;
}
}
This code i have used inside a controller action method
$request = $this->getRequest();
$getHeaderReferer=$request->getHeader('Referer');
if (!empty($getHeaderReferer))
{
$prevsingletrackurl = $getHeaderReferer->getUri(); // get previous url
//echo "<br>previous usrl=>".$prevsingletrackurl;
$controller = $this->getEvent()->getRouteMatch()->getParam('controller'); // get controller name
//**** code to get previous url route , controller name , action/method name starts
$request->setUri($prevsingletrackurl);
$router =$this->getServiceLocator()->get('Router');// this gives instance of /Zend/Mv/Router/Http/TreeRouteStack
//echo "<br>router=>".$router->toString();
$routeMatch = $router->match($request); // this gives instance of /Zend/Mv/Router/Http/RouteMatch
$routename="";
if( $routeMatch instanceof RouteMatch )
{
$urlwholeroutedataAr=$routeMatch->getParams();
if(!empty($urlwholeroutedataAr))
{
$controllerdata=$urlwholeroutedataAr['controller'];
$actionmethod=$urlwholeroutedataAr['action'];
if(array_key_exists('trackdata',$urlwholeroutedataAr))
{
$trackdata=$urlwholeroutedataAr['trackdata'];
}
$controllerdataAr=explode("\\",$controllerdata);
if(count($controllerdataAr)>0)
{
$controllername=end($controllerdataAr);
}
}
$routename=$routeMatch->getMatchedRouteName();
}
}