如果动作不存在,则重定向到控制器


Zend redirect to controller if action not exist

例如,我有动作example.com/books/list

但是我写错了example.com/books/lists,动作lists不存在,如果动作不存在如何重定向到controller/index

在执行操作前检查,我可以使用preDispatch(),但是如何检查此操作是否存在呢?

自定义错误控制器,使其重定向到404页面或做任何你想做的行为

这是一个检查操作是否存在的函数。它接受Zend_Controller_Request_Abstract作为参数并返回boolean:

private function _actionExists($request) { 
            $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher(); 
            
            // Check controller 
            if (!$dispatcher->isDispatchable($request)) { 
                    return false; 
            } 
            
            // Check action 
            $controllerClassName = $dispatcher->formatControllerName( $request->getControllerName() ); 
            $controllerClassFile = $controllerClassName . '.php'; 
            if ($request->getModuleName() != $dispatcher->getDefaultModule()) { 
                    $controllerClassName = ucfirst($request->getModuleName()) . '_' . $controllerClassName; 
            } 
            try { 
                    require_once 'Zend/Loader.php'; 
                    Zend_Loader::loadFile($controllerClassFile, $dispatcher->getControllerDirectory($request->getModuleName())); 
                    $actionMethodName = $dispatcher->formatActionName($request->getActionName()); 
                    if (in_array($actionMethodName, get_class_methods($controllerClassName))) { 
                            return true; 
                    } 
                    return false; 
            } catch(Exception $e) { 
                    return false; 
            } 
    }

详情请参阅此连结

如果该操作不存在(函数返回false),则重定向到索引路由:

$this->_helper->redirector($action, $controller, $module);
编辑:

@MuhannadA。Alhariri和@php-dev状态分别在他们的回答和评论中,这也可以通过自定义ErrorController来处理,我们只是比较error_handlerZend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION。这是一个帖子,给出了一个定制的错误控制器

你能试一下这段代码吗

$classMethods = get_class_methods($className);
if(!in_array("__call", $classMethods) && !in_array($this->getActionMethod($request), $classMethods))
return false;