views:

357

answers:

2

For a new CMS i've developed a Pages module that allows me to manage the site's tree structure. Each page is reachable from the url http://www.example.com/pageslug/ where pageslug identifies the page being called.

What I want to achieve now is a route that allows me to route all incoming requests to a single PagesController unless it's a request to an existing controller (like images for example).

It's easy enough to catch all requests to the Pages Controller but how to exclude existing controllers? This is my module bootstrap. How can i achieve this in the most preferrable way

<?php

class Default_Bootstrap extends Zend_Application_Module_Bootstrap
{

    protected function _initRoute()
    {
        $this->bootstrap('frontController');

        /* @var $frontcontroller Zend_Controller_Front */
        $frontcontroller = $this->getResource('frontController');

        $router = $frontcontroller->getRouter();
        $router->addRoute(
            'all',
            new Zend_Controller_Router_Route('*',
                array('controller' => 'pages',
                      'action'     => 'view')
            )
        );

    }

}
+2  A: 

Zend routes work in order - if you add a second route after your first, it will take precedence if it matches. In my own Zend project I've got a bunch of routes, the first of which is much like yours, a catch all route. However, anything below it that matches the url overrides it - so just try adding slightly more specific routes (if all your /user/ requests go to your user_controller, add a /user/* route)

Fake51
Thanks, sounds like a plan!
ChrisR
+2  A: 

Making your pages controller default, and adding a route for every existing controller might get very messy very quickly, and you have to change it every time you add a controller.

An alternative might be to customize the ErrorController. Since in the event of a missing controller, the framework will throw a Zend_Controller_Dispatcher_Exception which will propagate through to the error handler as an EXCEPTION_NO_CONTROLLER, you can just check for that type and forward to your pages controller.

If you're feeling masochistic, you could also write a custom route class that returns false if the controller exists and handles all routes if not. This is probably the best option in terms of roles and responsibilities, but also the most complex to implement.

Duncan