2011-12-09 32 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')? –