Search code examples
phpzend-framework

Zend redirect to controller if action not exist


For example I have action example.com/books/list

But I made mistake and write example.com/books/lists, action lists not exist, how to redirect to controller/index if action not exist.

To check before go to action I can use preDispatch(), but how to check do this action exist ?


Solution

  • Here is a function to check weither an action exists or not. It takes as parameter Zend_Controller_Request_Abstract and returns a 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; 
                } 
        }
    

    Pleaser see this link for more details.

    And then if the action effectively does not exists (the function returns false), redirect to your index route :

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

    EDIT :

    AS @MuhannadA.Alhariri and @php-dev state respectively in their answer and comment, this can be also handled by customizing the ErrorController within we have just to compare the error_handler with Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION. Here is a post which gives a customized error controller.