Simplest PHP Routing framework .. ?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2008-09-22T15:42:52Z Indexed on 2010/05/01 11:17 UTC
Read the original article Hit count: 286

I'm looking for the simplest implementation of a routing framework in PHP, in a typical PHP environment (Running on Apache, or maybe nginx) ..

It's the implementation itself I'm mostly interested in, and how you'd accomplish it.

I'm thinking it should handle URL's, with the minimal rewriting possible, (is it really a good idea, to have the same entrypoint for all dynamic requests?!), and it should not mess with the querystring, so I should still be able to fetch GET params with $_GET['var'] as you'd usually do..

So far I have only come across .htaccess solutions that puts everything through an index.php, which is sort of okay. Not sure if there are other ways of doing it.

How would you "attach" what URL's fit to what controllers, and the relation between them? I've seen different styles.

One huge array, with regular expressions and other stuff to contain the mapping.

The one I think I like the best is where each controller declares what map it has, and thereby, you won't have one huge "global" map, but a lot of small ones, each neatly separated.

So you'd have something like:

class Root {
    public $map = array(
        'startpage' => 'ControllerStartPage'
        );
}

class ControllerStartPage {
    public $map = array(
        'welcome' => 'WelcomeControllerPage'
        );
}

// Etc ...

Where:

'http://myapp/' // maps to the Root class
'http://myapp/startpage' // maps to the ControllerStartPage class
'http://myapp/startpage/welcome' // maps to the WelcomeControllerPage class
'http://myapp/startpage/?hello=world' // Should of course have $_GET['hello'] == 'world'

What do you think? Do you use anything yourself, or have any ideas?

I'm not interested in huge frameworks already solving this problem, but the smallest possible implementation you could think of. I'm having a hard time coming up with a solution satisfying enough, for my own taste.

There must be something pleasing out there that handles a sane bootstrapping process of a PHP application without trying to pull a big magic hat over your head, and force you to use "their way", or the highway! ;)

© Stack Overflow or respective owner

Related posts about php

Related posts about best-practices