1

我用 PHP 构建了一个自定义站点,它几乎就像一个 CMS,在这里我将有类别、子类别和页面/帖子,所以我预期的 URL 就像

mysite.com/category/sub-category/page-name/

并且这个层次结构不是恒定的,我可能会得到 3 个或更多子类别,而且我也会在同一个 URL 中有分页参数,比如

mysite.com/category/sub-category/page-name/6

所以,在我的网站 index.php 只会像在其他 CMS 中一样处理所有 URL,但我不确定如何拆分这个 url 以及如何知道哪个是页面名称、哪个分页参数、哪个是类别参数等等,请帮助我实现这一目标。

4

1 回答 1

0

您所追求的被称为“前端控制器”,它是一个处理进入您的应用程序的每个请求的单个 PHP 文件。

正如 RiggsFolly 所提到的,大多数 PHP 框架都内置了这个。这是 Symfony 的前端控制器(我最喜欢的 PHP 框架)

// index.php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals();
$path = $request->getPathInfo(); // the URI path being requested

if (in_array($path, array('', '/'))) {
    $response = new Response('Welcome to the homepage.');
} elseif ($path == '/contact') {
    $response = new Response('Contact us');
} else {
    $response = new Response('Page not found.', 404);
}
$response->send();
于 2013-10-22T09:21:23.647 回答