您无法在控制器__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';
}
}