RESTful API 是現代微服務架構的標準協議。本文提供基於 PHP cURL 擴展的完整服務端路由分發架構與客戶端封裝類,支持標準 HTTP 動詞、資源導向設計、Token 驗證、統一響應格式。
<?php
class ApiServer {
private $method = '';
protected $params = [];
protected $resource = '';
protected $resourceId = null;
public function __construct() {
$this->authorize(); // 1. 驗證簽名
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
$this->parseResource(); // 2. 解析資源路徑
$this->parseParams(); // 3. 解析請求參數
$this->dispatch(); // 4. 分發處理
}
// 驗證簽名認證
private function authorize() {
$token = $_SERVER['HTTP_CLIENT_TOKEN'] ?? '';
$sign = $_SERVER['HTTP_CLIENT_CODE'] ?? '';
$expected = md5(substr(md5($token), 8, 24) . $token);
if ($sign !== $expected) {
$this->respond(401, 'Unauthorized: Invalid signature');
}
}
// RESTful 路由解析: /users/123 → resource=users, id=123
private function parseResource() {
$pathinfo = $_SERVER['PATH_INFO'] ?? '/';
$parts = array_filter(explode('/', trim($pathinfo, '/')));
$this->resource = $parts[0] ?? '';
$this->resourceId = $parts[1] ?? null;
}
// 統一參數獲取 (GET/POST/PUT/DELETE 統一從 $_GET 獲取,實際項目建議解析 php://input)
private function parseParams() {
$this->params = $_GET; // 簡化演示
}
// 動作分發
private function dispatch() {
$method = '_' . $this->method;
if (method_exists($this, $method)) {
$this->$method();
} else {
$this->respond(405, 'Method Not Allowed');
}
}
// 統一響應格式
protected function respond(int $code, mixed $data = null, string $message = '') {
http_response_code($code);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'code' => $code,
'message' => $message ?: ($code === 200 ? 'Success' : 'Error'),
'data' => $data,
'timestamp' => time()
], JSON_UNESCAPED_UNICODE);
exit;
}
// 子類實現具體業務
protected function _get() { $this->respond(200, ['resource' => $this->resource]); }
protected function _post() { $this->respond(201, ['created' => true]); }
protected function _put() { $this->respond(200, ['updated' => true]); }
protected function _delete() { $this->respond(200, ['deleted' => true]); }
}
// 入口文件
$api = new ApiServer();
?>
| HTTP 方法 | 路徑模式 | 語義 | 處理方法 |
|---|---|---|---|
| GET | /users | 列表查詢 | _get() |
| POST | /users | 創建資源 | _post() |
| GET | /users/{id} | 單條詳情 | _get() |
| PUT | /users/{id} | 全量更新 | _put() |
| PATCH | /users/{id} | 部分更新 | _patch() |
| DELETE | /users/{id} | 刪除資源 | _delete() |
<?php
class RestClient {
private $baseUrl;
private $token;
private $timeout = 30;
public function __construct(string $baseUrl, string $token) {
$this->baseUrl = rtrim($baseUrl, '/');
$this->token = $token;
}
public function request(string $method, string $resource, ?int $id = null, array $data = []): array {
$url = $this->baseUrl . '/' . ltrim($resource, '/');
if ($id !== null) $url .= '/' . $id;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => strtoupper($method),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Client-Token: ' . $this->token,
'Client-Code: ' . $this->generateSign($this->token),
],
]);
if (in_array($method, ['post', 'put', 'patch'])) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
} elseif ($method === 'get' && $data) {
$url .= '?' . http_build_query($data);
curl_setopt($ch, CURLOPT_URL, $url);
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error) throw new RuntimeException("cURL Error: $error");
$result = json_decode($response, true);
if ($httpCode >= 400) {
throw new RuntimeException("API Error [$httpCode]: " . ($result['message'] ?? 'Unknown'));
}
return $result['data'] ?? [];
}
private function generateSign(string $token): string {
return md5(substr(md5($token), 8, 24) . $token);
}
// 便捷方法
public function get(string $resource, ?int $id = null, array $query = []) { return $this->request('get', $resource, $id, $query); }
public function post(string $resource, array $data) { return $this->request('post', $resource, null, $data); }
public function put(string $resource, int $id, array $data) { return $this->request('put', $resource, $id, $data); }
public function delete(string $resource, int $id) { return $this->request('delete', $resource, $id); }
}
// 使用示例
$client = new RestClient('https://api.example.com', 'your_secret_token');
$users = $client->get('users');
$user = $client->get('users', 123);
$newUser = $client->post('users', ['name' => 'John', 'email' => 'john@example.com']);
$client->put('users', 123, ['name' => 'John Updated']);
$client->delete('users', 123);
?>
location /api/ {
# 必須傳遞 PATH_INFO 給 PHP
fastcgi_split_path_info ^(/api)(.*)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root/api/index.php;
}