PHP RESTful
讲解 REST 架构核心约束与无框架原生 PHP RESTful 服务分层实现(数据仓储、URI 重写路由、状态码基类、内容协商处理器),并在 PHP 8.4 CLI 实测 JSON/HTML/XML 响应与 200/404/406 状态码。
学完这一章,你能够
- 讲解 REST 架构核心约束与无框架原生 PHP RESTful 服务分层实现(数据仓储、URI 重写路由、状态码基类、内容协商处理器),并在 PHP 8.4 CLI 实测 JSON/HTML/XML 响应与 200/404/406 状态码。
REST 架构原则与无框架实现目标
REST(Representational State Transfer,表述性状态转移)是一套面向 Web 的架构约束与设计风格。符合 REST 风格的 RESTful Web API 围绕三要素组织:简洁直观的资源地址 URI(例如 `http://example.com/resources/`)、通过互联网媒体类型(JSON、XML、HTML 或 YAML)传输的资源表述,以及借助标准 HTTP 方法(GET、POST、PUT、DELETE 等)表达对资源的语义化操作。
本章不依赖第三方框架,使用原生 PHP 构建一套完整的 RESTful 服务示例,涵盖服务数据层编写、符合 REST 规范的 URI 路径映射、根据请求头 `Accept` 协商返回 JSON/XML/HTML 格式、依据结果返回准确 HTTP 状态码(如 `200 OK`、`404 Not Found`),以及使用 REST 客户端发起测试的完整工作流。
资源数据层、URI 重写规则与请求分发控制器
服务数据类(如 `Site` / 本站实验中的 `SiteRepository`)封装资源集合与按主键查询方法。需要注意传统教材中若未命中 ID 时回退返回第 1 条记录,会导致客户端无法收到 `404`;更符合 REST 语义的做法是在 ID 不存在时返回空数组,交由处理器统一响应 `404 Not Found`。
为提供简洁的资源地址,Web 服务器需将可读路径映射到前端控制器。本例约定两条规则:获取全部站点列表 `/site/list/`(如本地部署 `http://localhost/restexample/site/list/`)以及按编号获取单个站点 `/site/list/3/`。在 Apache 下通过 `.htaccess` 开启 `RewriteEngine on` 与 `Options +FollowSymlinks`,使用两条 `RewriteRule` 将 `^site/list/$` 与 `^site/list/([0-9]+)/$` 分别重写为 `RestController.php?view=all` 与 `RestController.php?view=single&id=$1`(附带 `[nc,qsa]` 标志)。
前端控制器 `RestController.php` 读取查询参数 `view`(以及单条查询时的 `id`),通过 `switch ($view)` 分发至处理器的 `getAllSites()` 或 `getSite($id)`;若 `view` 缺失或未匹配,则返回 `404`。本站 PHP 8.4.27 实验脚本的 `matchRewriteRoute()` 精确复现了上述正则路由分发逻辑。
HTTP 状态码基类与多格式内容协商处理器
基础响应类 `SimpleRest` 维护常见 1xx–5xx HTTP 状态码到原因短语的映射表,并统一组装状态行与 `Content-Type` 响应头(注意部分旧示例在兜底分支误写为未定义变量 `$status[500]`,本站实测实现已修正为 `$httpStatus[$statusCode] ?? $httpStatus[500]`)。
处理类 `SiteRestHandler` 继承 `SimpleRest`,读取请求数据后先判定 `200` 或 `404`,再依据客户端 `Accept` 头分别编码为 `application/json`、`text/html`(HTML 表格,带 `htmlspecialchars` 转义防 XSS)或 `application/xml`(使用 `SimpleXMLElement` 生成合法元素名 `<site id="3">BlueSky</site>`,规避以纯数字作 XML 标签名的语法错误);对不支持的媒体类型返回 `406 Not Acceptable`。
在本地部署后直接通过浏览器访问 `/site/list/` 时,浏览器默认发送含 `text/html` 的 `Accept` 头,因此页面会展示表格化的站点列表响应(参考截图未缓存,已记入待处理项)。
REST 客户端联调、本地实测结果与附件说明
使用浏览器 REST 调试工具(如 Advanced REST Client、Postman 或 curl)并显式指定 `Accept: application/json` 请求 `/site/list/` 时,服务端返回 `HTTP/1.1 200 OK`、`Content-Type: application/json` 与全部 6 条站点 JSON 对象。本站 PHP 8.4.27 CLI 实测确认:列表接口返回 6 条记录且键 `3` 对应 `'BlueSky'`,查询不存在的 `/site/list/999/` 精确返回 `HTTP/1.1 404 Not Found` 与 `{"error":"No sites found!"}`。
将请求地址改为 `/site/list/3/` 并切换 `Accept` 头为 `text/html` 与 `application/xml` 时,本站实测分别返回 `200` 状态与 `<table border='1'><tr><td>3</td><td>BlueSky</td></tr></table>`,以及经 `simplexml_load_string()` 可正常解析的 XML 文档(`id='3'`、文本 `'BlueSky'`);而发送 `Accept: image/png` 则准确触发 `HTTP/1.1 406 Not Acceptable`。
原页面文末曾提供示例工程压缩包下载入口;因来源站点处于继承停止抓取状态,本站未向外部抓取该压缩包,而是随本章直接附带可离线运行的完整 PHP 8.4 REST 控制器与内容协商实验脚本 `explore-restful.php` 供本地学习验证。
在 PHP 8.4 CLI 离线实测原生 RESTful 路由分发、内容协商与 HTTP 状态码
展开查看收起
<?php
declare(strict_types=1);
class SiteRepository
{
/** @var array<int, string> */
private array $sites = [
1 => 'AlphaDocs',
2 => 'CloudHub',
3 => 'BlueSky',
4 => 'DataGrid',
5 => 'StreamAPI',
6 => 'OpenTools',
];
/** @return array<int, string> */
public function getAllSites(): array
{
return $this->sites;
}
/** @return array<int, string> */
public function getSite(int $id): array
{
if (!isset($this->sites[$id])) {
return [];
}
return [$id => $this->sites[$id]];
}
}
class SimpleRest
{
private string $httpVersion = 'HTTP/1.1';
public function buildHeaders(string $contentType, int $statusCode): array
{
$statusMessage = $this->getHttpStatusMessage($statusCode);
return [
'status_line' => $this->httpVersion . ' ' . $statusCode . ' ' . $statusMessage,
'status_code' => $statusCode,
'content_type' => $contentType,
];
}
public function getHttpStatusMessage(int $statusCode): string
{
$httpStatus = [
200 => 'OK',
201 => 'Created',
204 => 'No Content',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
500 => 'Internal Server Error',
];
return $httpStatus[$statusCode] ?? $httpStatus[500];
}
}
class SiteRestHandler extends SimpleRest
{
private SiteRepository $repo;
public function __construct(?SiteRepository $repo = null)
{
$this->repo = $repo ?? new SiteRepository();
}
public function handle(string $view, ?int $id, string $accept): array
{
if ($view === 'all') {
$rawData = $this->repo->getAllSites();
} elseif ($view === 'single' && $id !== null) {
$rawData = $this->repo->getSite($id);
} else {
$rawData = [];
}
if ($rawData === []) {
$statusCode = 404;
$rawData = ['error' => 'No sites found!'];
} else {
$statusCode = 200;
}
if (str_contains($accept, 'application/json')) {
$contentType = 'application/json';
$body = $this->encodeJson($rawData);
} elseif (str_contains($accept, 'text/html')) {
$contentType = 'text/html';
$body = $this->encodeHtml($rawData);
} elseif (str_contains($accept, 'application/xml')) {
$contentType = 'application/xml';
$body = $this->encodeXml($rawData);
} else {
$statusCode = 406;
$contentType = 'application/json';
$body = $this->encodeJson(['error' => 'Not Acceptable']);
}
return [
'headers' => $this->buildHeaders($contentType, $statusCode),
'body' => $body,
];
}
public function encodeHtml(array $data): string
{
$html = "<table border='1'>";
foreach ($data as $k => $v) {
$html .= '<tr><td>' . htmlspecialchars((string)$k, ENT_QUOTES, 'UTF-8')
. '</td><td>' . htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8') . '</td></tr>';
}
return $html . '</table>';
}
public function encodeJson(array $data): string
{
return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
public function encodeXml(array $data): string
{
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><sites></sites>');
foreach ($data as $k => $v) {
$node = $xml->addChild('site', htmlspecialchars((string)$v, ENT_XML1, 'UTF-8'));
$node->addAttribute('id', (string)$k);
}
return trim($xml->asXML());
}
}
function matchRewriteRoute(string $uriPath): array
{
$trimmed = trim($uriPath, '/');
if (preg_match('#^site/list$#i', $trimmed)) {
return ['view' => 'all', 'id' => null];
}
if (preg_match('#^site/list/([0-9]+)$#i', $trimmed, $m)) {
return ['view' => 'single', 'id' => (int)$m[1]];
}
return ['view' => '', 'id' => null];
}
$handler = new SiteRestHandler();
$cases = [];
// Case 1: GET /site/list/ with Accept: application/json -> 200 OK
$r1 = matchRewriteRoute('/site/list/');
$res1 = $handler->handle($r1['view'], $r1['id'], 'application/json');
$decoded1 = json_decode($res1['body'], true);
$c1Actual = [
'status_line' => $res1['headers']['status_line'],
'content_type' => $res1['headers']['content_type'],
'count' => count($decoded1),
'site_3' => $decoded1['3'],
];
$c1Expected = [
'status_line' => 'HTTP/1.1 200 OK',
'content_type' => 'application/json',
'count' => 6,
'site_3' => 'BlueSky',
];
$cases[] = [
'name' => 'rest_list_json_200',
'passed' => $c1Actual === $c1Expected,
'expected' => $c1Expected,
'actual' => $c1Actual,
];
// Case 2: GET /site/list/3/ content negotiation (text/html & application/xml)
$r2 = matchRewriteRoute('/site/list/3/');
$resHtml = $handler->handle($r2['view'], $r2['id'], 'text/html');
$resXml = $handler->handle($r2['view'], $r2['id'], 'application/xml');
$parsedXml = simplexml_load_string($resXml['body']);
$c2Actual = [
'html_status' => $resHtml['headers']['status_code'],
'html_type' => $resHtml['headers']['content_type'],
'html_body' => $resHtml['body'],
'xml_status' => $resXml['headers']['status_code'],
'xml_type' => $resXml['headers']['content_type'],
'xml_site_id' => (string)$parsedXml->site[0]['id'],
'xml_site_name' => (string)$parsedXml->site[0],
];
$c2Expected = [
'html_status' => 200,
'html_type' => 'text/html',
'html_body' => "<table border='1'><tr><td>3</td><td>BlueSky</td></tr></table>",
'xml_status' => 200,
'xml_type' => 'application/xml',
'xml_site_id' => '3',
'xml_site_name' => 'BlueSky',
];
$cases[] = [
'name' => 'rest_single_html_and_xml_200',
'passed' => $c2Actual === $c2Expected,
'expected' => $c2Expected,
'actual' => $c2Actual,
];
// Case 3: GET /site/list/999/ -> 404 Not Found
$r3 = matchRewriteRoute('/site/list/999/');
$res3 = $handler->handle($r3['view'], $r3['id'], 'application/json');
$c3Actual = [
'status_line' => $res3['headers']['status_line'],
'content_type' => $res3['headers']['content_type'],
'body' => json_decode($res3['body'], true),
];
$c3Expected = [
'status_line' => 'HTTP/1.1 404 Not Found',
'content_type' => 'application/json',
'body' => ['error' => 'No sites found!'],
];
$cases[] = [
'name' => 'rest_not_found_404',
'passed' => $c3Actual === $c3Expected,
'expected' => $c3Expected,
'actual' => $c3Actual,
];
// Case 4: Rewrite URI routing & 406 Not Acceptable
$rUnknown = matchRewriteRoute('/site/unknown/');
$res406 = $handler->handle('all', null, 'image/png');
$c4Actual = [
'route_all' => $r1,
'route_single' => $r2,
'route_unknown' => $rUnknown,
'not_acceptable_status' => $res406['headers']['status_line'],
];
$c4Expected = [
'route_all' => ['view' => 'all', 'id' => null],
'route_single' => ['view' => 'single', 'id' => 3],
'route_unknown' => ['view' => '', 'id' => null],
'not_acceptable_status' => 'HTTP/1.1 406 Not Acceptable',
];
$cases[] = [
'name' => 'rest_uri_rewrite_router',
'passed' => $c4Actual === $c4Expected,
'expected' => $c4Expected,
'actual' => $c4Actual,
];
echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
XML 规范禁止元素标签名以数字开头,直接 addChild('3', 'BlueSky') 会生成非法 XML;应改用合法固定标签名(如 <site>)并将数字主键存为属性(<site id="3">BlueSky</site>)。