从零开始:用PHP打造你的第一个RESTful API
PHP接口开发示例代码详解
在现代Web开发中,接口(API)是前后端交互的核心。PHP作为一种广泛使用的服务器端脚本语言,非常适合用于开发RESTful API。下面我们将详细介绍如何使用PHP开发一个简单的RESTful API,并提供一个完整的示例代码。
1. 环境准备
首先,确保你已经安装了PHP和Web服务器(如Apache或Nginx)。你可以使用XAMPP、WAMP或LAMP等集成环境来快速搭建开发环境。
2. 创建项目结构
为了保持代码的整洁和可维护性,我们建议使用MVC(模型-视图-控制器)架构。以下是一个简单的项目结构:
my_api/
├── index.php
├── controllers/
│ └── UserController.php
├── models/
│ └── UserModel.php
├── routes/
│ └── api.php
└── config/
└── database.php
3. 配置数据库
<?php
$host = 'localhost';
$dbname = 'my_database';
$username = 'root';
$password = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("数据库连接失败: " . $e->getMessage());
}
?>
4. 创建模型
在models/UserModel.php
中创建一个简单的用户模型:
<?php
class UserModel {
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
public function getUsers() {
$stmt = $this->pdo->query("SELECT * FROM users");
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function getUserById($id) {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $id]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function createUser($name, $email) {
$stmt = $this->pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(['name' => $name, 'email' => $email]);
return $this->pdo->lastInsertId();
}
public function updateUser($id, $name, $email) {
$stmt = $this->pdo->prepare("UPDATE users SET name = :name, email = :email WHERE id = :id");
return $stmt->execute(['id' => $id, 'name' => $name, 'email' => $email]);
}
public function deleteUser($id) {
$stmt = $this->pdo->prepare("DELETE FROM users WHERE id = :id");
return $stmt->execute(['id' => $id]);
}
}
?>
5. 创建控制器
在controllers/UserController.php
中创建一个用户控制器:
<?php
require_once '../models/UserModel.php';
class UserController {
private $userModel;
public function __construct($pdo) {
$this->userModel = new UserModel($pdo);
}
public function getUsers() {
return $this->userModel->getUsers();
}
public function getUserById($id) {
return $this->userModel->getUserById($id);
}
public function createUser($name, $email) {
return $this->userModel->createUser($name, $email);
}
public function updateUser($id, $name, $email) {
return $this->userModel->updateUser($id, $name, $email);
}
public function deleteUser($id) {
return $this->userModel->deleteUser($id);
}
}
?>
6. 配置路由
在routes/api.php
中配置API路由:
<?php
require_once '../config/database.php';
require_once '../controllers/UserController.php';
$userController = new UserController($pdo);
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));
$input = json_decode(file_get_contents('php://input'), true);
switch ($request[0]) {
case 'users':
if ($method == 'GET') {
if (isset($request[1])) {
echo json_encode($userController->getUserById($request[1]));
} else {
echo json_encode($userController->getUsers());
}
} elseif ($method == 'POST') {
$name = $input['name'];
$email = $input['email'];
$id = $userController->createUser($name, $email);
echo json_encode(['id' => $id]);
} elseif ($method == 'PUT' && isset($request[1])) {
$id = $request[1];
$name = $input['name'];
$email = $input['email'];
$success = $userController->updateUser($id, $name, $email);
echo json_encode(['success' => $success]);
} elseif ($method == 'DELETE' && isset($request[1])) {
$id = $request[1];
$success = $userController->deleteUser($id);
echo json_encode(['success' => $success]);
} else {
http_response_code(404);
echo json_encode(['error' => 'Not Found']);
}
break;
default:
http_response_code(404);
echo json_encode(['error' => 'Not Found']);
break;
}
?>
7. 配置入口文件
在index.php
中配置入口文件:
<?php
require_once 'routes/api.php';
?>
8. 测试API
现在你可以通过以下URL测试你的API:
- 获取所有用户:
GET /users
- 获取单个用户:
GET /users/{id}
- 创建用户:
POST /users
(Body:{"name": "John Doe", "email": "john@example.com"}
) - 更新用户:
PUT /users/{id}
(Body:{"name": "John Doe", "email": "john@example.com"}
) - 删除用户:
DELETE /users/{id}
9. 总结
通过以上步骤,我们实现了一个简单的RESTful API。这个示例展示了如何使用PHP进行接口开发,包括数据库连接、模型、控制器和路由的配置。你可以根据实际需求扩展这个示例,添加更多的功能和安全性措施。