Dev*_*per 5 php zend-framework2
在zf1中,我们可以使用获取控制器和动作名称
$controller = $this->getRequest()->getControllerName();
$action = $this->getRequest()->getActionName();
Run Code Online (Sandbox Code Playgroud)
我们如何在zf2中实现这一目标?
更新:我试图让他们使用
echo $this->getEvent()->getRouteMatch()->getParam('action', 'NA');
echo $this->getEvent()->getRouteMatch()->getParam('controller', 'NA');
Run Code Online (Sandbox Code Playgroud)
但我收到了错误
Fatal error: Call to a member function getParam() on a non-object
Run Code Online (Sandbox Code Playgroud)
我喜欢在__construct()方法中获取它们;
理想情况下,我想检查是否没有定义Action将执行noaction()方法.我会检查使用php方法method_exists.
Al-*_*unk 13
更简单:
$controllerName =$this->params('controller');
$actionName = $this->params('action');
Run Code Online (Sandbox Code Playgroud)
您无法在控制器__construct()方法中访问这些变量,但可以在dispatch方法和onDispatch方法中访问它们。
但是如果您想检查操作是否存在,在 zf2 中已经有一个针对 notFoundAction 的内置函数,如下所示
public function notFoundAction()
{
parent::notFoundAction();
$response = $this->getResponse();
$response->setStatusCode(200);
$response->setContent("Action not found");
return $response;
}
Run Code Online (Sandbox Code Playgroud)
但如果您仍然喜欢手动执行此操作,您可以使用调度方法执行此操作,如下所示
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';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20758 次 |
| 最近记录: |