简介:为什么需要在 PHP 中构建 REST API?
REST API(表述性状态转移)是一种架构风格,允许不同应用程序通过 HTTP 相互通信。如今,现代网络服务离不开 API:移动应用、SPA 前端、支付系统集成——所有这些都需要快速且清晰的数据交换接口。
PHP 仍然是后端开发最流行的语言之一。你可以用纯 PHP 编写一个完整的 REST API,而无需臃肿的框架——只需不到 30 分钟。本文将带您通过一个实际示例,实现用于管理待办事项列表的 CRUD 操作(创建、读取、更新、删除)。
1. 环境设置与项目结构
为此,你需要准备:
- 一个本地服务器(Open Server、XAMPP、MAMP 或 PHP 内置服务器)
- PHP 7.4 或更高版本
- 一个代码编辑器(VS Code、PhpStorm)
创建一个根文件夹 rest-api-php,并在其中创建以下文件:
rest-api-php/├── index.php (入口点,路由器)├── config.php (数据库设置)├── api/│ ├── tasks.php (任务 CRUD)│ └── helpers.php (辅助函数)└── .htaccess (将请求重定向到 index.php)1.1. 设置 .htaccess 以实现简洁 URL
为了将所有请求路由到单一入口点,请在根目录创建 .htaccess 文件:
RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php [QSA,L]如果你使用 PHP 内置服务器,只需在项目文件夹中运行:php -S localhost:8000。
2. 创建路由器和基础 API
打开 index.php——这是我们的主处理器。它将分析 HTTP 方法和 URI,并调用必要的函数。
2.1. index.php —— 入口点
<?phpheader("Content-Type: application/json; charset=UTF-8");header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");header("Access-Control-Allow-Headers: Content-Type, Authorization");
require_once 'config.php';require_once 'api/helpers.php';
$method = $_SERVER['REQUEST_METHOD'];$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);$uri = rtrim($uri, '/');
// 简单路由if ($uri === '/api/tasks') { require_once 'api/tasks.php'; handleTasks($method);} elseif (preg_match('/^\\/api\\/tasks\\/(\\d+)$/', $uri, $matches)) { require_once 'api/tasks.php'; handleTask($method, (int)$matches[1]);} else { sendResponse(['error' => 'Endpoint not found'], 404);}?>我们处理两个路由:/api/tasks(列表/创建)和 /api/tasks/{id}(特定任务)。
2.2. helpers.php —— 辅助函数
<?phpfunction sendResponse($data, $status = 200) { http_response_code($status); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit;}
function getJsonInput() { $input = file_get_contents('php://input'); return json_decode($input, true) ?? [];}?>3. 数据库操作与 CRUD 功能实现
让我们在 MySQL 中创建一个简单的 tasks 表:
CREATE TABLE tasks ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, status ENUM('pending', 'completed') DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);文件 config.php:
<?php$host = 'localhost';$dbname = 'rest_api_db';$username = 'root';$password = '';
try { $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO