Is there a reusable router / dispatcher for PHP?

2019-03-20 21:20发布

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.

1条回答
Emotional °昔
2楼-- · 2019-03-20 22:07

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);
查看更多
登录 后发表回答