in zf1, we can get controller and action name using
$controller = $this->getRequest()->getControllerName();
$action = $this->getRequest()->getActionName();
How we can achieve this in zf2?
UPDATE: I tried to get them using
echo $this->getEvent()->getRouteMatch()->getParam('action', 'NA');
echo $this->getEvent()->getRouteMatch()->getParam('controller', 'NA');
But I am getting error
Fatal error: Call to a member function getParam() on a non-object
I like to get them in __construct() method;
Ideally I would like to check if there is no Action is defined it will execute noaction() method. I would check using php method method_exists.
Even simpler:
you can't access these variables in controller
__construct()
method, but you can access them indispatch
method andonDispatch
method.but if you would like to check whether action exist or not, in zf2 there is already a built in function for that notFoundAction as below
but if you still like to do it manually you can do this using dispatch methods as follow
You will get module , controller and action name like this in Zf2 inside your controller...