Routing

The standard routing uses the parsed URL data in the CoreUrl object to determine the controller to use from the first URL segment and the method in that controller from the second segment.

For example if the URL were http://www.example.org/foo/bar/ then the controller would be FooController and the method would be displayBar(). If there is no second segment then the displayIndex() method is called. If there are no segments at all then the default controller defined in the boostrap is used with the displayIndex() method.

Routing allows you to re-route a URL to use a controller and method that break from this standard. The routing overrides are set in the site configuration file.

Routing rules can use regular expressions and backreferences (eg. $1) are automatically replaced.


Routing Example

//route http://www.example.org/foo/bar/ to DemoController and displayBaz()
$arrConfig['Routes']['^/foo/bar/$'] = '/demo/baz/';

//route http://www.example.org/foo/[segment]/ to DemoController display[Segment]
$arrConfig['Routes']['^/foo/([^/]+)/$'] = '/demo/$1/';

//route the miscellaneous footer pages to MiscController display[Segment]
$arrConfig['Routes']['^/(about|help|contact|terms|privacy)/?$'] = '/misc/$1/';

//route the index to SiteController displaySplash()
$arrConfig['Routes']['^/?$'] = '/site/splash/';

Minified URL Routing

Sometimes your URLs will contain a string in them for SEO purposes. For example, http://example.org/blogs/42/i-miss-arrested-development/ where 42 is the blog ID and i-miss-arrested-development is the blog title converted into a format suitable for a URL. You could minify this URL to http://example.org/b/42/ and route it through a redirect method that looks up the title and then sends a 301 permanent redirect header.

//route the minified URLs through a redirect controller
$arrConfig['Routes']['^/b/([0-9]+)/?$'] = '/site/redirect/type=blog/id=$1/';

This is an example of a redirect method that would go in SiteController.class.php. It could also use the CacheHooks class to cache the redirect header.

protected function displayRedirect() {
    $objUrl = AppRegistry::get('Url');
    switch ($objUrl->getFilter('type')) {
        case 'blog':
            if ($intBlogId = $objUrl->getFilter('id')) {
                AppLoader::includeModel('BlogModel');
                $objBlog = new BlogModel();
                if ($objBlog->loadById($intBlogId) && $objBlogRecord = $objBlog->first()) {
                    $strLocation = sprintf('/%s/blogs/%d/%s/', $objUrl->getBaseUrl(), $intBlogId, $objBlogRecord->get('urlkey'));
                }
            }
                
        default:
            trigger_error(AppLanguage::translate('Invalid redirect type'));
            break;
    }
    
    if (isset($strLocation)) {
        $objDisplay = AppDisplay::getInstance();
        $objDisplay->setStatusCode(301);
        $objDisplay->appendHeader('location: ' . $strLocation);
    } else {
        $this->error(404);
    }
}