微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在PHP框架中的漂亮的URL

我知道你可以在htaccess中添加规则,但是我发现PHP框架没有这样做,不知何故,你仍然有相当的URL。 他们如何做到这一点,如果服务器不知道的URL规则?

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

Apache mod_rewrite一个文件夹的子文件夹(通过内部redirect)

重写规则隐藏端口从Rails服务器的URL?

PHP重写URL并保存发布的数据

mod_rewrite的部分url为GEtvariables

Mod_ReWrite / ReWriteMap使用数据库查找脚本的URL

这通常通过以下规则将所有请求路由到单个入口点(一个基于请求执行不同代码文件)来完成:

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

一个简单的小例子:

<?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 (eg 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 。 希望这可以帮助你理解这里发生的事情。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐