如何获得在ZF2控制器和动作名称(How to get controller and action

2019-07-31 06:30发布

在ZF1,我们可以用得到的控制器和动作名称

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

我们如何能在ZF2实现这一目标?

更新:我试着使用,让他们

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

理想情况下,我想检查是否有没有被定义它将执行无动作()方法操作。 我会检查使用PHP方法method_exists。

Answer 1:

更简单:

$controllerName =$this->params('controller');
$actionName = $this->params('action');


Answer 2:

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

但如果你想检查行动中是否存在与否,在ZF2已经有一个内置的函数,该函数notFoundAction如下

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

但如果你还是喜欢做手工,你可以使用调度方法如下做到这一点

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


Answer 3:

您将获得模块,控制器和动作名称像这样ZF2控制器...里面

$controllerClass = get_class($this);
$moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
$tmp = substr($controllerClass, strrpos($controllerClass, '\\')+1 );
$controllerName = str_replace('Controller', "", $tmp);

//set 'variable' into layout...
$this->layout()->currentModuleName      = strtolower($moduleNamespace);
$this->layout()->currentControllerName  = strtolower($controllerName);
$this->layout()->currentActionName      = $this->params('action');


Answer 4:

$controllerName = strtolower(Zend_Controller_Front::getInstance()->getRequest()->getControllerName());


文章来源: How to get controller and action name in zf2