Django-like routing in PHP

05 Jul 2008 16:06

As I've recently work with Django, the way it does the URL-based routing seemed really cool for me. I missed that in PHP, so I decided to code something like this.

Here is a class that uses (extends) my Controller class that does the routing:

class Controller_Ajax_Auth extends Controller_Ajax {
    protected $routes = Array(
        ':^info$:'                => 'info',
        ':^challenge$:'            => 'challenge',
        ':^login$:'                => 'login',
        ':^logout$:'            => 'logout',
    protected function info($url) {
        $r = Array();
        /* something */
    protected function challenge($url) {
        /* $q = something */
    protected function login($url) {
        /* set $auth to true if logged */
    protected function logout($url) {
        /* logout */

This mainly routes URLs info, challenge, login and logout to corresponding methods in the same object.

But you can route out of the object to other Controller subclass instance:

    protected $routes = Array(
        ':^auth/(.*)$:'            => 'Controller_Ajax_Auth',

This gets URL and passes what's after auth/ to the new object of class Controller_Ajax_Auth (see the code above). Generally the first ()s in the left side of each line define what's passed to the method/object on the right side.

The controller has abstract errorHandler and defaultAction methods that need to be overridden. The first is called when a exception is thrown in a performed action. The latter is called, when routing comes to some object and then no routing line matches.

More posts on this topic


Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License