PHP框架中的美化URLs
P粉176980522
P粉176980522 2023-10-30 09:40:09

我知道您可以在 htaccess 中添加规则,但我发现 PHP 框架不会这样做,并且不知何故您仍然拥有漂亮的 URL。如果服务器不知道 URL 规则,他们如何做到这一点?

我一直在寻找 Yii 的 url 管理器类,但我不明白它是如何做到的。

P粉176980522
P粉176980522

全部回复(1)
P粉801904089

这通常是通过将所有请求路由到单个入口点(根据请求执行不同代码的文件)来完成的,规则如下:

# 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"]) 与路由列表进行比较 - 与请求匹配的模式到控制器操作(在 MVC 应用程序中)或其他操作的映射执行路径。框架通常包含一个可以从请求本身推断控制器和操作的路由,作为备份路由。

一个简单的小例子:

 '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;

与第一个配置相结合,这是一个简单的脚本,允许您使用像 domain.com/about 这样的 URL。希望这可以帮助您了解这里发生的事情。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!