我正在做我的第一个单入口网站,根据结果,我看不出有什么好处。
我已经实现了以下内容:
- .htaccess 将所有请求重定向到根目录下的 index.php
- 解析 Url 并将每个/segment/作为一个元素存储在数组中
- 第一段指示要包含的文件夹(例如“users”»“/pages/users/index.php”)。
- 每个文件夹的index.php文件解析segments数组中的剩余元素,直到数组为空。
- 如果segments数组中没有元素,则包含每个文件夹的content.php文件,表示到达目标文件
示例
文件结构([] 中的文件夹):
- [根]
- index.php
- [页数]
- [用户]
- index.php
- content.php
- [个人资料]
- index.php
- content.php
- [编辑]
- index.php
- content.php
- [其他页面]
- index.php
- content.php
- [用户]
请求:http://mysite.com/users/profile/
.htaccess 将请求重定向到 http://mysite.com/index.php
URL 被解析并且段数组包含:[1] 用户,[2] 个人资料
index.php 将 [1] 映射到“pages/users/index.php”,因此包含该文件
pages/users/index.php 将 [2] 映射到 pages/users/profile/index.php,因此包含该文件
由于段数组中没有其他元素,因此包含当前文件夹(pages/users/profile)中的 contents.php 文件。
我并没有真正看到这样做比拥有包含网站组件的功能(例如 include_header()、include_footer() 等)有什么好处,所以我得出结论,我做的事情非常错误。我只是不确定它是什么。
最佳答案
您拥有的这个版本缺少一些功能,只能用作非常简单的前端 Controller 模式。
大多数系统不会将 URL 映射到作为页面的单个 PHP 文件 - 它们将 URL 路径映射到知道如何构建页面的 Controller .
此外,并不是所有的 URL 都需要映射到直接文件。例如,查看 github.com/[username]/[repo]
。您无法创建数百万个 bob/ajaxstuff/index.php
文件 - 您需要使用正则表达式告诉 Controller 您想要此项目的写入页面。
$app->get('/:username/:repo', function ($username, $repo) {
echo "Looking at $username's $repo";
});
要真正掌握如何正确使用它,我建议您使用功能齐全的路由系统,例如简单的 Slim Framework。 .
如果您想了解有关路由设计和理论的更多信息,我建议您阅读 php-router's自述文件和优秀URL Design来自 warpspire 的帖子。
关于php - 单项执行出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13015981/