Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reusable router / dispatcher for PHP?

I'm using a simple framework that handles requests based on query parameters.

http://example.com/index.php?event=listPage
http://example.com/index.php?event=itemView&id=1234

I want to put clean urls in front of this so you can access it this way:

http://example.com/list
http://example.com/items/1234

I know how routes and dispatching works, and I could write it myself. But I would rather take advantage of all the code out there that already solves this problem. Does anyone know of a generic library or class that provides this functionality, but will let me return whatever I want from a route match? Something like this.

$Router = new Router();
$Router->addRoute('/items/:id', 'itemView', array( 'eventName' => 'itemView' ));

$Router->resolve( '/items/1234' );
// returns array( 'routeName' => 'itemView',
//                'eventName' => 'itemView,
//                'params' => array( 'id' => '1234' ) )

Essentially I would be able to do the dispatching myself based on the values resolved from the path. I wouldn't mind lifting this out of a framework if it's not too much trouble (and as long as the license permits). But usually I find the routing/dispatching in frameworks to be just a little too integrated to repurpose like this. And my searches seem to suggest that people are writing this themselves if they're not using frameworks.

A good solution would support the following:

  • specify routes with colon notation or regex notation
  • parse parameters out of routes and return them somehow
  • support fast reverse lookup like so:

    $Router->get( 'itemView', array( 'id' => '1234' ) );
    // returns 'items/1234'
    

Any help is appreciated.

like image 280
Marco Avatar asked Mar 18 '11 06:03

Marco


1 Answers

GluePHP might be very close to what you want. It provides one simple service: to maps URLs to Classes.

require_once('glue.php');

$urls = array(
    '/' => 'index',
    '/(?P<number>\d+)' => 'index'
);

class index {
    function GET($matches) {
        if (array_key_exists('number', $matches)) {
            echo "The magic number is: " . $matches['number'];
        } else {
            echo "You did not enter a number.";
        }
    }
}

glue::stick($urls);
like image 150
Andrew Moore Avatar answered Oct 16 '22 06:10

Andrew Moore