1
0
mirror of https://github.com/dannyvankooten/AltoRouter.git synced 2025-07-31 13:40:16 +02:00

first commit

This commit is contained in:
Danny van Kooten
2012-07-31 20:50:36 +02:00
commit ebbfe7804a
4 changed files with 283 additions and 0 deletions

3
.htaccess Normal file
View File

@@ -0,0 +1,3 @@
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

192
AltoRouter.php Normal file
View File

@@ -0,0 +1,192 @@
<?php
class AltoRouter {
private $routes = array();
private $namedRoutes = array();
private $basePath = '';
public function setBasePath($basePath) {
$this->basePath = $basePath;
}
/**
* Map a route to a target
*/
public function map($method, $route, $target, array $args = array()) {
$route = $this->basePath . $route;
$this->routes[] = array($method, $route, $target);
if(isset($args['name'])) {
$this->namedRoutes[$args['name']] = $route;
}
}
/**
* Reversed routing
*
* Generate the URL for a named route. Replace regexes with supplied parameters
*/
public function generate($routeName, array $params = array()) {
// Check if named route exists
if(!isset($this->namedRoutes[$routeName])) {
throw new \Exception("Route '{$routeName}' does not exist.");
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
$url = $route;
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if(isset($params[$param])) {
$url = str_replace(substr($block,1), $params[$param], $url);
}
}
}
return $url;
}
/**
* Match a given Request Url against stored routes
*/
public function match($requestUrl = null, $requestMethod = null) {
// set Request Url if it isn't passed as parameter
if($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// Strip query string (?a=b) from Request Url
if (false !== strpos($requestUrl, '?')) {
$requestUrl = strstr($requestUrl, '?', true);
}
// set Request Method if it isn't passed as a parameter
if($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
// Force request_order to be GP
// http://www.mail-archive.com/internals@lists.php.net/msg33119.html
$_REQUEST = array_merge($_GET, $_POST);
foreach($this->routes as $handler) {
list($method, $_route, $target) = $handler;
$methods = explode('|', $method);
$method_match = false;
// Check if request method matches. If not, abandon early. (CHEAP)
foreach($methods as $method) {
if (strcasecmp($requestMethod, $method) === 0) {
$method_match = true;
break;
}
}
// Method did not match, continue to next route.
if(!$method_match) continue;
// Check for a wildcard (matches all)
if ($_route === '*') {
$match = true;
} elseif (isset($_route[0]) && $_route[0] === '@') {
$match = preg_match('`' . substr($_route, 1) . '`', $requestUrl, $params);
} else {
$route = null;
$regex = false;
$j = 0;
$n = isset($_route[0]) ? $_route[0] : null;
$i = 0;
// Find the longest non-regex substring and match it against the URI
while (true) {
if (!isset($_route[$i])) {
break;
} elseif (false === $regex) {
$c = $n;
$regex = $c === '[' || $c === '(' || $c === '.';
if (false === $regex && false !== isset($_route[$i+1])) {
$n = $_route[$i + 1];
$regex = $n === '?' || $n === '+' || $n === '*' || $n === '{';
}
if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) {
continue 2;
}
$j++;
}
$route .= $_route[$i++];
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params);
}
if(isset($match) && $match > 0) {
if($params) {
foreach($params as $key => $value) {
if(is_numeric($key)) unset($params[$key]);
}
}
return array(
'target' => $target,
'params' => $params
);
}
}
return false;
}
/**
* Compile the regex for a given route (EXPENSIVE)
*/
private function compileRoute($route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$match_types = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/]++'
);
foreach ($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if (isset($match_types[$type])) {
$type = $match_types[$type];
}
if ($pre === '.') {
$pre = '\.';
}
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. '))'
. ($optional !== '' ? '?' : null);
$route = str_replace($block, $pattern, $route);
}
}
return "`^$route$`";
}
}

62
README.MD Normal file
View File

@@ -0,0 +1,62 @@
**AltoRouter is an alternative router to PHP-Router, also lightning fast and flexible.
AltoRouter is heavily inspired by [klein.php](https://github.com/chriso/klein.php/).
* Flexible regular expression routing (inspired by [Sinatra](http://www.sinatrarb.com/))
* Reversed routing
* Named parameter in routes
## Getting started
1. PHP 5.3.x is required
2. Setup URL rewriting so that all requests are handled by **index.php**
3. Include AltoRouter, map your routes and match a request.
4. Have a look at the supplied example file (index.php).
## Routing
```php
$router = new AltoRouter();
$router->setBasePath('/AltoRouter');
$router->map('GET|POST','/', 'home#index', array('name' => 'home'));
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', array('name' => 'users_show'));
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', array('name' => 'users_do'));
```
You can use the following limits on your named parameters. AltoRouter will create the correct regexes.
```php
Some examples
* // Match all request URIs
[i] // Match an integer
[i:id] // Match an integer as 'id'
[a:action] // Match alphanumeric characters as 'action'
[h:key] // Match hexadecimal characters as 'key'
[:action] // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*] // Catch all (lazy, stops at the next trailing slash)
[*:trailing] // Catch all as 'trailing' (lazy)
[**:trailing] // Catch all (possessive - will match the rest of the URI)
.[:format]? // Match an optional parameter 'format' - a / or . before the block is also optional
Some more complicated examples
/posts/[*:title][i:id] // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]? // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]? // Matches the typical /controller/action format
```
## License
(MIT License)
Copyright (c) 2012 Danny van Kooten <dannyvankooten@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

26
index.php Normal file
View File

@@ -0,0 +1,26 @@
<?php
require 'AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/AltoRouter');
$router->map('GET|POST','/', 'home#index', array('name' => 'home'));
$router->map('GET','/users/', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', array('name' => 'users_show'));
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', array('name' => 'users_do'));
// match current request
$match = $router->match();
?>
<h1>AltoRouter</h3>
<h3>Current request: </h3>
<pre>
Target: <?php var_dump($match['target']); ?>
Params: <?php var_dump($match['params']); ?>
</pre>
<h3>Try these requests: </h3>
<p><a href="<?php echo $router->generate('home'); ?>">GET <?php echo $router->generate('home'); ?></a></p>
<p><a href="<?php echo $router->generate('users_show', array('id' => 5)); ?>">GET <?php echo $router->generate('users_show', array('id' => 5)); ?></a></p>
<p><form action="<?php echo $router->generate('users_do', array('id' => 10, 'action' => 'update')); ?>" method="post"><button type="submit"><?php echo $router->generate('users_do', array('id' => 10, 'action' => 'update')); ?></button></form></p>