在PHP框架pretty网址 [英] Pretty URLs in PHP frameworks

查看:228
本文介绍了在PHP框架pretty网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,你可以在.htaccess中加入规则,但我看到的PHP框架不这样做,不管怎样,你还是有pretty的URL。他们怎么做,如果服务器不知道的URL规则?

I know that you can add rules in htaccess, but I see that PHP frameworks don't do that and somehow you still have pretty URLs. How do they do that if the server is not aware of the URL rules?

我一直在寻找的Yii的的网址管理器类,但我不明白它是怎么做的。

I've been looking Yii's url manager class but I don't understand how it does it.

推荐答案

这通常是由路由到一个单一的入口点像的规则(即执行根据请求的不同code文件)的所有请求完成:

This is usually done by routing all requests to a single entry point (a file that executes different code based on the request) with a rule like:

# 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应用程序)或执行的另一条路径。框架通常包括可以推断,从请求本身的控制器和行动,作为备份路由的路由。

This file then compares the request ($_SERVER["REQUEST_URI"]) against a list of routes - a mapping of a pattern matching the request to a controller action (in MVC applications) or another path of execution. Frameworks often include a route that can infer the controller and action from the request itself, as a backup route.

有一个小的,简单的例子:

A small, simplified example:

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

与第一配置组合

,这是一个简单的脚本,让你使用像网​​址domain.com/about 。希望这可以帮助您怎么在这里上的感觉。

Combined with the first configuration, this is a simple script that will allow you to use URLs like domain.com/about. Hope this helps you make sense of what's going on here.

这篇关于在PHP框架pretty网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆