Skip to content

Instantly share code, notes, and snippets.

@zeuxisoo
Created September 26, 2011 08:22
Show Gist options
  • Save zeuxisoo/1241844 to your computer and use it in GitHub Desktop.
Save zeuxisoo/1241844 to your computer and use it in GitHub Desktop.
PHP url router like rails
RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
<?php
require_once 'route.php';
print_r(Route::map("/user/:id/:name"));
Route::map("/user/:id/:name", function($id, $name) {
echo $id.' - '.$name;
});
?>
<?php
// Reference: http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/
class Route {
public static function request_uri() {
$uri = '';
if (empty($_SERVER['PATH_INFO']) === false) {
$uri = $_SERVER['PATH_INFO'];
}else{
if (isset($_SERVER['REQUEST_URI']) === true) {
$scheme = empty($_SERVER['HTTPS']) === true || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https';
$uri = parse_url($scheme.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'], PHP_URL_PATH);
}elseif (isset($_SERVER['PHP_SELF']) === true) {
$uri = $_SERVER['PHP_SELF'];
}else{
return "";
}
$request_uri = isset($_SERVER['REQUEST_URI']) === true ? $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'];
$script_name = $_SERVER['SCRIPT_NAME'];
$base_uri = strpos($request_uri, $script_name) === 0 ? $script_name : str_replace('\\', '/', dirname($script_name));
$base_uri = rtrim($base_uri, '/');
if ($base_uri !== '' && strpos($uri, $base_uri) === 0) {
$uri = substr($uri, strlen($base_uri));
}
return '/' . ltrim($uri, '/');
}
}
public static function map($pattern_uri, $callback = null) {
$request_uri = self::request_uri();
// Get names: :id, :name
preg_match_all('/:([0-9a-zA-Z_]+)/', $pattern_uri, $names, PREG_PATTERN_ORDER);
$names = $names[0];
// Form: /user/:id/:name
// To : /user/([a-zA-Z0-9_\+\-%]+)/([a-zA-Z0-9_\+\-%]+)/?
$pattern_uri_regex = preg_replace_callback('/:[[0-9a-zA-Z_]+/', array(__class__, 'pattern_uri_regex'), $pattern_uri);
$pattern_uri_regex .= '/?';
// Match pattern uri regex on request uri, fill params
$params = array();
if (preg_match('@^' . $pattern_uri_regex . '$@', $request_uri, $values)) {
array_shift($values);
foreach($names as $index => $value) {
$params[substr($value, 1)] = urldecode($values[$index]);
}
if (is_callable($callback) === true) {
call_user_func_array($callback, array_values($params));
}
}
return $params;
}
public static function pattern_uri_regex($matches) {
return '([a-zA-Z0-9_\+\-%]+)';
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment