php RESTful实现
RESTful API 实现基础
RESTful API 是一种基于 HTTP 协议的架构风格,通过资源标识符(URI)和标准方法(GET/POST/PUT/DELETE)操作资源。PHP 实现需遵循以下核心原则:
- 无状态性:每次请求包含完整信息,不依赖会话
- 资源化:数据抽象为资源,通过 URI 访问
- 统一接口:使用标准 HTTP 方法
- 可缓存性:响应应明确是否可缓存
路由与请求处理
使用 .htaccess 文件实现 URL 重写,将请求路由到前端控制器:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
创建核心路由器解析请求:
$request = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
$paths = explode('/', trim($request, '/'));
$resource = array_shift($paths);
$id = count($paths) ? array_shift($paths) : null;
资源控制器设计
为每个资源创建独立控制器类,实现 CRUD 操作:
class ProductController {
public function listProducts() {
header('Content-Type: application/json');
echo json_encode(['data' => Product::all()]);
}
public function getProduct($id) {
$product = Product::find($id);
if(!$product) {
header("HTTP/1.0 404 Not Found");
return;
}
echo json_encode($product);
}
}
响应格式标准化
统一响应格式包含状态码、数据和消息:
function jsonResponse($data, $status = 200, $message = null) {
header('Content-Type: application/json');
http_response_code($status);
echo json_encode([
'status' => $status,
'data' => $data,
'message' => $message
]);
exit;
}
认证与安全实现
JWT 认证示例:
function authenticate() {
$headers = getallheaders();
if(!isset($headers['Authorization'])) {
jsonResponse(null, 401, 'Unauthorized');
}
try {
$token = str_replace('Bearer ', '', $headers['Authorization']);
return JWT::decode($token, SECRET_KEY, ['HS256']);
} catch (Exception $e) {
jsonResponse(null, 401, 'Invalid token');
}
}
错误处理机制
全局异常处理器捕获各类错误:
set_exception_handler(function($e) {
$status = method_exists($e, 'getStatusCode')
? $e->getStatusCode()
: 500;
jsonResponse([
'error' => $e->getMessage(),
'trace' => DEBUG_MODE ? $e->getTrace() : null
], $status);
});
版本控制策略
通过 URI 或 Accept 头实现 API 版本管理:
/api/v1/products
或
Accept: application/vnd.company.api+json; version=1.0
性能优化技巧
数据库查询优化:
$products = Product::with('category')
->select('id', 'name', 'price')
->paginate(20);
响应缓存控制:
header('Cache-Control: public, max-age=3600');
header('ETag: "'.md5($content).'"');
文档自动生成
使用 OpenAPI 规范生成文档:
paths:
/products:
get:
summary: List all products
responses:
200:
description: A list of products
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Product'
测试策略
PHPUnit 测试示例:

class ApiTest extends TestCase {
public function testGetProduct() {
$client = new Client();
$response = $client->get('/api/products/1');
$this->assertEquals(200, $response->getStatusCode());
$this->assertJson($response->getBody());
}
}






