Skip to content

Commit

Permalink
updated readme
Browse files Browse the repository at this point in the history
  • Loading branch information
moagrius committed Feb 7, 2014
1 parent 47eeaad commit 92c4491
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 1 deletion.
4 changes: 4 additions & 0 deletions .htaccess
@@ -0,0 +1,4 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
18 changes: 17 additions & 1 deletion README.md
@@ -1,4 +1,20 @@
RegexRouter
===========

PHP class to route with regular expressions. Extremely small.
PHP class to route with regular expressions. Extremely small. Follows every conceivable best-practice - SRP, SoC, DI, IoC, bfft...

Usage
===========

The only actual code is RegexRouter.php. index.php and the .htaccess file are just demoing usage. The 3 together in a TLD will function.

Setup

===========

1. make sure you're sending all requests to a front controller (either through apache conf directly or htaccess)
1. include or require RegexRouter.php `require_once 'RegexRouter.php';`
1. instantiate a new instance `$router = new RegexRouter();`
1. add some routes `$router->route('/^\/some\/pattern$/', <closure>);`
1. pass it the uri (either REQUEST_URI or any string for unit testing) `$router->execute($_SERVER['REQUEST_URI']);`

29 changes: 29 additions & 0 deletions RegexRouter.php
@@ -0,0 +1,29 @@
<?php

class RegexRouter {

private $routes = array();

public function route($pattern, $callback) {
$this->routes[$pattern] = $callback;
}

public function execute($uri) {
foreach ($this->routes as $pattern => $callback) {
if (preg_match($pattern, $uri, $params) === 1) {
array_shift($params);
return call_user_func_array($callback, array_values($params));
}
}
}

}

/**
* Usage...
* $router = new RegexRouter();
* $router->route('/^blog\/(\w+)\/(\d+)\/?$/', function($category, $id){
print "category={$category}, id={$id}";
});
* $router->execute($_SERVER['REQUEST_URI']);
*/
9 changes: 9 additions & 0 deletions index.php
@@ -0,0 +1,9 @@
<?php

require_once 'RegexRouter.php';

$router = new RegexRouter();
$router->route('/^\/blog\/(\w+)\/(\d+)\/?$/', function($category, $id){
print "category={$category}, id={$id}";
});
$router->execute($_SERVER['REQUEST_URI']);

0 comments on commit 92c4491

Please sign in to comment.