user2102919
user2102919

Reputation: 21

Simple PHP Routing Project

I need to create a simple routing mechanism that takes a request like: /foo/bar and translates it to FooController->barAction(); I have to use a single script as an access point to load these controller classes and action methods. I also cannot use any external frameworks or libraries to accomplish this task. This needs to be able to be run on a PHP 5.3 Server with Apache.

Below is what I've written already, but I'm having trouble getting it to work:

class Router {

    private static $routes = array();

    private function __construct() {}
    private function __clone() {}

    public static function route($pattern, $callback) {
        $pattern = '/' . str_replace('/', '\/', $pattern) . '/';
        self::$routes[$pattern] = $callback;
    }

    public static function execute() {
        $url = $_SERVER['REQUEST_URI'];
        $base = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME']));
        if (strpos($url, $base) === 0) {
            $url = substr($url, strlen($base));
        }
        foreach (self::$routes as $pattern => $callback) {
            if (preg_match($pattern, $url, $params)) {
                array_shift($params);
                return call_user_func_array($callback, array_values($params));
            }
        }
    }
}

I'm trying to at least execute my current script which is based off another simple Router, but I cannot actually get an output using

Router::route('blog/(\w+)/(\d+)', function($category, $id){
  print $category . ':' . $id;
});
Router::execute();

Upvotes: 0

Views: 3572

Answers (1)

iLLin
iLLin

Reputation: 760

Instead of trying to break out the PATH. Why not use .htaccess instead.

So you could have internal URL's that look like this:

index.php?module=MODULE&action=INDEX

Then use .htaccess to provide the paths in the URL and the route them accordingly.

www.mydomain.com/MODULE/INDEX

This post can help with the rewriting regex for creating pritty urls in htaccess

There might be a better one, was just a quick google search.

This way you can access like this:

$module = $_GET['module'];
$action = $_GET['action];

Then you can do checks to corresponding actions in your router to check if it exists and then re-route accordingly.

Upvotes: 1

Related Questions