我正在使用ZF2中的服务,我需要将控制器和操作从已构建的路径中获取。 那么有可能以某种方式从路线中获取动作和控制器吗?
扩展说明:
我尝试使用
$controller = $this->params()->fromRoute('controller');
$action = $this->params()->fromRoute('action');
但是我需要id fx我得到一个URL / accessadmin / addRole女巫是命名空间\ controller AccessAdmin \ Controller \ IndexController - > addRoleAction()
所以我需要一种方法将路由转换为AccessAdmin \ Controller \ IndexController并获取Action。
解决了结果
<?php
use Zend\Http\Request;
class IndexController extends AbstractActionController {
public function indexAction()
{
// Uri example.
$uri = '/accessadmin/resources/addRole/4';
$request = new Request();
$request->setUri($uri);
/** @var $router \Zend\Mvc\Router\Http\TreeRouteStack */
$router = $this->getServiceLocator()->get('Router');
$routeMatch = $router->match( $request );
if($routeMatch !== null ) {
$controller = $this->getServiceLocator()->get('Config')['controllers']['invokables'][$routeMatch->getParam('controller')];
$action = $routeMatch->getParam('action');
}
// Lazy test
var_dump($controller);
var_dump($action);
return new ViewModel();
}
}
?>
答案 0 :(得分:0)
如果您要求从当前路线获取这些参数,那么它非常简单:
use Zend\Mvc\Controller\AbstractActionController;
class Index extends AbstractActionController {
public function indexAction() {
$controller = $this->params()->fromRoute('controller');
$action = $this->params()->fromRoute('action');
return new ViewModel();
}
}
您可能还想知道给定URL字符串的控制器/操作参数是什么。在这种情况下,你可以像这样使用RouteMatch:
class Index extends AbstractActionController {
public function indexAction() {
$uri = '/accessadmin/addRole';
$request = new Request();
$request->setUri($uri);
/** @var $router \Zend\Mvc\Router\Http\TreeRouteStack */
$router = $this->getServiceLocator()->get('Router');
$routeMatch = $router->match( $request );
if($routeMatch !== null ) {
$controller = $routeMatch->getParam('controller');
$action = $routeMatch->getParam('action');
}
}
}