【发布时间】:2014-01-14 16:11:25
【问题描述】:
使用 Zend 应用程序,在将用户重定向到该页面之前,我需要验证 URI 是否存在(在我的应用程序内部)。如何执行此控制?
【问题讨论】:
标签: zend-framework redirect uri url-redirection
使用 Zend 应用程序,在将用户重定向到该页面之前,我需要验证 URI 是否存在(在我的应用程序内部)。如何执行此控制?
【问题讨论】:
标签: zend-framework redirect uri url-redirection
有几种方法可以做到这一点...见下文。
我认为最好的方法是使用 ACL MVC 规则 - 为您的应用程序增加安全性,并可用于检查资源(模型/控制器/操作)是否存在。
选项 1
构建类名并获取它的方法以查看您的操作是否存在。使用get_class_methods 或ReflectionClass::getMethods
/**
* @param string $controller name of controller e.g. "index"
* @param string $action name of action e.g. "index", "myAction"
* @param string $module (optional) name of the current module
* @return boolean
*/
protected function _isControllerAction($controller, $action, $module = '')
{
$module = ($module == 'default') ? '' : $module;
$class = ucfirst($module) . ucfirst($controller) . 'Controller';
$methods = get_class_methods($class);
return in_array("{$action}Action", $methods);
}
选项 2
您可以检查模块/控制器是否可调度。这不会检查操作并与请求混淆!如果你这样做,那么添加额外的代码来恢复请求状态。
protected function isDispatchableController()
{
$this->getRequest()
->setModuleName('default')
->setControllerName('index');
$dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
/* @var $dispatcher Zend_Controller_Dispatcher_Standard */
return $dispatcher->isDispatchable($this->getRequest());
}
选项 3
从技术上讲,您可以跳过所有这些检查并实现默认 ErrorHandler 并让它重定向到 ErrorController... 然后为 404 添加特殊处理
选项 4
如果您使用 ACL,您可以检查资源是否存在以及用户是否可以访问它。 这是Zend ACL MVC Integration上的好文章
【讨论】:
如果您使用的是 Zend Framework 2,这非常简单。
假设我们要检查一个 URI 是否与注册的路由器匹配,如果这与当前 url 不同,则重定向用户。
$goto = 'http://www.mysite.tld/admin';
$request = $this->getRequest();
$request->setUri($goto);
if ($routeToBeMatched = $this->getServiceLocator()->get('Router')->match($request)) {
$currentRouteMatchName = $this->getEvent()->getRouteMatch()->getMatchedRouteName();
if ($routeToBeMatched->getMatchedRouteName() != $currentRouteMatchName) {
return $this->redirect()->toRoute($goto);
}
}
【讨论】: