如何在 zf2 中获取控制器和动作名称

问题描述:

在 zf1 中,我们可以使用

in zf1, we can get controller and action name using

$controller = $this->getRequest()->getControllerName();
$action = $this->getRequest()->getActionName();

我们如何在 zf2 中实现这一点?

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

但我收到错误

Fatal error: Call to a member function getParam() on a non-object

我喜欢在 __construct() 方法中获取它们;

I like to get them in __construct() method;

理想情况下,我想检查是否没有定义 Action 它将执行 noaction() 方法.我会检查使用 php 方法 method_exists.

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.

你不能在控制器__construct()方法中访问这些变量,但是你可以在dispatch方法中访问它们code> 方法和 onDispatch 方法.

you can't access these variables in controller __construct() method, but you can access them in dispatch method and onDispatch method.

但是如果你想检查动作是否存在,在 zf2 中已经有一个内置函数用于 notFoundAction 如下

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

 public function notFoundAction()
{
    parent::notFoundAction();
    $response = $this->getResponse();
    $response->setStatusCode(200);
    $response->setContent("Action not found");
    return $response;   
} 

但是如果您仍然喜欢手动执行此操作,则可以使用如下调度方法执行此操作

but if you still like to do it manually you can do this using dispatch methods as follow

namespace Mynamespace\Controller;

use Zend\Mvc\Controller\AbstractActionController;

use Zend\Stdlib\RequestInterface as Request;
use Zend\Stdlib\ResponseInterface as Response;
use Zend\Mvc\MvcEvent;

class IndexController extends AbstractActionController 
{

    public function __construct()
    {


    }        

      public function notFoundAction()
    {
        parent::notFoundAction();
        $response = $this->getResponse();
        $response->setStatusCode(200);
        $response->setContent("Action not found");
        return $response;   
    }

    public function dispatch(Request $request, Response $response = null)
    {
        /*
         * any customize code here
         */

        return parent::dispatch($request, $response);
    }
    public function onDispatch(MvcEvent $e)
    {
        $action = $this->params('action');
        //alertnatively 
        //$routeMatch = $e->getRouteMatch();
        //$action = $routeMatch->getParam('action', 'not-found');

        if(!method_exists(__Class__, $action."Action")){
           $this->noaction();
        }

        return parent::onDispatch($e);
    }
    public function noaction()
    {        
        echo 'action does not exits';   
    }
}