2011-12-09 35 views
15

我知道你可以在htaccess中添加規則,但是我發現PHP框架並沒有這樣做,並且不知何故,你仍然擁有漂亮的網址。如果服務器不知道URL規則,他們如何做到這一點?PHP框架中的漂亮網址

我一直在找Yii的url manager class,但我不明白它是如何做到的。

# Redirect everything that doesn't match a directory or file to index.php 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule .* index.php [L] 

這個文件然後比較請求($_SERVER["REQUEST_URI"]):

+5

查看我的回答[如何從PHP腳本中更改URL的外觀](http://stackoverflow.com/questions/8392965/how-to-change-appearance-of-url-from-within-a- php-script/8392997#8392997) 大多數框架所做的是將所有請求重定向到一個處理所有內容的文件。你忘記了代碼中的 – Ibu

回答

15

這通常是由路由所有請求的單一入口點有如下規則(執行基於請求不同的代碼文件)來完成針對路由列表 - 將匹配請求的模式映射到控制器操作(在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。希望這可以幫助你理解這裏發生的事情。

+1

:在GET參數中添加url:'RewriteRule(。*)index.php?url = $ 1 [QSA,L]' –

+1

嗨Olivier,沒有必要將url作爲參數因爲它在$ _SERVER ['REQUEST_URI']'中可用。 – Ross

+0

你確定*它不會是最終重寫的URL(即'$ _SERVER ['REQUEST_URI']'=='index.php')? –