Is there a reusable router / dispatcher for PHP?

给你一囗甜甜゛ 提交于 2019-12-04 12:08:44

问题


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:


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);


来源:https://stackoverflow.com/questions/5348837/is-there-a-reusable-router-dispatcher-for-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!