這通常是由路由所有請求的單一入口點有如下規則(執行基於請求不同的代碼文件)來完成針對路由列表 - 將匹配請求的模式映射到控制器操作(在MVC應用程序中)或另一個執行路徑。框架通常包括一條可以從請求本身推斷出控制器和動作的路線,作爲備用路線。
一個小的,簡化的例子:
<?php
// Define a couple of simple actions
class Home {
public function GET() { return 'Homepage'; }
}
class About {
public function GET() { return 'About page'; }
}
// Mapping of request pattern (URL) to action classes (above)
$routes = array(
'/' => 'Home',
'/about' => 'About'
);
// Match the request to a route (find the first matching URL in routes)
$request = '/' . trim($_SERVER['REQUEST_URI'], '/');
$route = null;
foreach ($routes as $pattern => $class) {
if ($pattern == $request) {
$route = $class;
break;
}
}
// If no route matched, or class for route not found (404)
if (is_null($route) || !class_exists($route)) {
header('HTTP/1.1 404 Not Found');
echo 'Page not found';
exit(1);
}
// If method not found in action class, send a 405 (e.g. Home::POST())
if (!method_exists($route, $_SERVER["REQUEST_METHOD"])) {
header('HTTP/1.1 405 Method not allowed');
echo 'Method not allowed';
exit(1);
}
// Otherwise, return the result of the action
$action = new $route;
$result = call_user_func(array($action, $_SERVER["REQUEST_METHOD"]));
echo $result;
與第一結構相結合,這是一個簡單的腳本,將允許您使用的URL像domain.com/about
。希望這可以幫助你理解這裏發生的事情。
查看我的回答[如何從PHP腳本中更改URL的外觀](http://stackoverflow.com/questions/8392965/how-to-change-appearance-of-url-from-within-a- php-script/8392997#8392997) 大多數框架所做的是將所有請求重定向到一個處理所有內容的文件。你忘記了代碼中的 – Ibu