PHP 實現 Rails 風格的路由器


由於在寫自己開發用的unframework東東
所以出於日後可能用得上的考慮,就生出了這個東西
主要支持了 :id 這些 constraints,另外還半支持自定義的規則
配合 .htaccess 應該就可以發揮 Route 路由效果了
初步記錄一下

1
2
3
4
5
6
7
8
9
// 由 Route 決定規則
Route::map("/user/:id/:name", function($id, $name) {
echo $id.' - '.$name;
});

// 自定義 :name 的規則
Route::map("/user/:id/:name#Zeuxis#", function($id, $name) {
echo $id.' - '.$name;
});
1
2
3
4
5
6
7
8
9
10
# Nginx 的 Rewrite
if (!-f $request_filename) {
rewrite ^/subfolder/(.*)$ /subfolder/index.php last;
}

# Apache 的 Rewrite
RewriteEngine On
RewriteBase /subfolder
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
// Author: Zeuixs Lo
class Route {

const NOT_MATCH_ROUTE = -1;

public static function request_uri() {
$uri = empty($_SERVER['PATH_INFO']) === false ? $_SERVER['PATH_INFO'] : $_SERVER['REQUEST_URI'];
}

public static function map($pattern_uri, $callback = null, $sensitive = false, $strict = false) {
$request_uri = self::request_uri();
$match_words = "/(?<!\\\):([a-zA-Z_][a-zA-Z_0-9]*)?(?:#(.*?)#)?/";

// Get all names such as :id, :name
preg_match_all($match_words, $pattern_uri, $names, PREG_PATTERN_ORDER);
$names = $names[1];

//[Form]: /user/:id, [To]: /user/([a-zA-Z0-9_\+\-%]+) OR /user/(custom rule)
$match_path = preg_replace_callback($match_words, array(__class__, "match_path"), $pattern_uri);
$match_path .= $strict === true ? '' : '/?';

$match_path = $sensitive === true ? "@".$match_path."@" : "@".$match_path."@i";

// Fill params
$params = array();
if (preg_match($match_path, $request_uri, $values) == true) {
array_shift($values);

foreach($names as $index => $name) {
$params[$name] = rawurldecode($values[$index]);
}

if (is_callable($callback) === true) {
call_user_func_array($callback, array_values($params));exit;
}
}

return $params;
}

public static function match_path($matches) {
return isset($matches[2]) === true ? '('.$matches[2].')' : '([a-zA-Z0-9_\+\-%]+)';
}

private static function error($type, $message = "") {
switch($type) {
case self::NOT_MATCH_ROUTE:
$message = "Not found matched route case by ".$message;
break;
}

exit(sprintf("<strong>[Error]:</strong> %s", $message));
}
}
?>