构建现代化、可维护的Web应用程序
PHP面向对象编程基础
类和对象的基本概念
面向对象编程(OOP)是PHP开发中的重要范式,它将数据和操作数据的方法封装在对象中。
基础类定义示例
<?php
class User {
// 属性
private $id;
private $username;
private $email;
private $createdAt;
// 构造方法
public function __construct($username, $email) {
$this->username = $username;
$this->email = $email;
$this->createdAt = date('Y-m-d H:i:s');
}
// Getter方法
public function getUsername() {
return $this->username;
}
public function getEmail() {
return $this->email;
}
// Setter方法
public function setEmail($email) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->email = $email;
return true;
}
return false;
}
// 业务逻辑方法
public function getProfileInfo() {
return "用户名: {$this->username}, 邮箱: {$this->email}";
}
}
// 使用示例
$user = new User("john_doe", "john@example.com");
echo $user->getProfileInfo();
?>
继承与多态
继承允许我们创建基于现有类的新类,多态则让我们使用统一的接口处理不同的对象类型。
继承示例
<?php
// 基类
abstract class Product {
protected $name;
protected $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
abstract public function getDescription();
public function getPrice() {
return $this->price;
}
}
// 子类 - 物理产品
class PhysicalProduct extends Product {
private $weight;
public function __construct($name, $price, $weight) {
parent::__construct($name, $price);
$this->weight = $weight;
}
public function getDescription() {
return "{$this->name} - 重量: {$this->weight}kg - 价格: ¥{$this->price}";
}
}
// 子类 - 数字产品
class DigitalProduct extends Product {
private $fileSize;
public function __construct($name, $price, $fileSize) {
parent::__construct($name, $price);
$this->fileSize = $fileSize;
}
public function getDescription() {
return "{$this->name} - 文件大小: {$this->fileSize}MB - 价格: ¥{$this->price}";
}
}
// 使用多态
$products = [
new PhysicalProduct("笔记本电脑", 5999, 2.5),
new DigitalProduct("电子书", 29.9, 15)
];
foreach ($products as $product) {
echo $product->getDescription() . "n";
}
?>
MVC架构模式详解
Model(模型)
负责数据处理和业务逻辑,与数据库直接交互。
- 数据验证和清洗
- 数据库操作
- 业务规则实现
- 数据关系管理
View(视图)
负责用户界面展示,不包含业务逻辑。
- HTML模板渲染
- 数据展示格式化
- 用户交互界面
- 响应式设计
Controller(控制器)
处理用户请求,协调模型和视图。
- 接收用户输入
- 调用模型方法
- 选择视图渲染
- 处理业务逻辑
MVC目录结构示例
project/
├── app/
│ ├── controllers/
│ │ ├── UserController.php
│ │ └── ProductController.php
│ ├── models/
│ │ ├── User.php
│ │ └── Product.php
│ └── views/
│ ├── user/
│ │ ├── index.php
│ │ └── profile.php
│ └── product/
│ ├── list.php
│ └── detail.php
├── config/
│ └── database.php
├── public/
│ └── index.php
└── vendor/
PDO数据库操作与安全
数据库连接类
使用PDO(PHP Data Objects)进行安全的数据库操作,防止SQL注入攻击。
数据库连接封装
<?php
class Database {
private $host = 'localhost';
private $dbname = 'myapp';
private $username = 'root';
private $password = '';
private $pdo;
private $error;
public function __construct() {
$dsn = "mysql:host={$this->host};dbname={$this->dbname};charset=utf8mb4";
try {
$this->pdo = new PDO($dsn, $this->username, $this->password);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->error = $e->getMessage();
throw new Exception("数据库连接失败: " . $this->error);
}
}
// 准备并执行SQL语句
public function query($sql, $params = []) {
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
} catch (PDOException $e) {
throw new Exception("SQL执行错误: " . $e->getMessage());
}
}
// 获取单条记录
public function fetch($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetch();
}
// 获取所有记录
public function fetchAll($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetchAll();
}
// 获取最后插入的ID
public function lastInsertId() {
return $this->pdo->lastInsertId();
}
}
?>
用户模型示例
结合面向对象和数据库操作,创建完整的用户管理系统。
<?php
class UserModel {
private $db;
public function __construct() {
$this->db = new Database();
}
// 创建用户
public function create($username, $email, $password) {
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password, created_at)
VALUES (:username, :email, :password, NOW())";
$params = [
':username' => $username,
':email' => $email,
':password' => $hashedPassword
];
$this->db->query($sql, $params);
return $this->db->lastInsertId();
}
// 根据ID查找用户
public function findById($id) {
$sql = "SELECT id, username, email, created_at FROM users WHERE id = :id";
return $this->db->fetch($sql, [':id' => $id]);
}
// 根据邮箱查找用户(登录验证)
public function findByEmail($email) {
$sql = "SELECT * FROM users WHERE email = :email";
return $this->db->fetch($sql, [':email' => $email]);
}
// 获取所有用户(分页)
public function getAll($page = 1, $limit = 10) {
$offset = ($page - 1) * $limit;
$sql = "SELECT id, username, email, created_at
FROM users
ORDER BY created_at DESC
LIMIT :limit OFFSET :offset";
$params = [
':limit' => $limit,
':offset' => $offset
];
return $this->db->fetchAll($sql, $params);
}
// 更新用户信息
public function update($id, $data) {
$allowedFields = ['username', 'email'];
$setParts = [];
$params = [':id' => $id];
foreach ($data as $key => $value) {
if (in_array($key, $allowedFields)) {
$setParts[] = "{$key} = :{$key}";
$params[":{$key}"] = $value;
}
}
if (empty($setParts)) {
return false;
}
$sql = "UPDATE users SET " . implode(', ', $setParts) . " WHERE id = :id";
$this->db->query($sql, $params);
return true;
}
}
?>
完整项目实战:用户管理系统
用户控制器实现
控制器负责处理HTTP请求,调用模型方法,并渲染视图。
<?php
class UserController {
private $userModel;
public function __construct() {
$this->userModel = new UserModel();
}
// 显示用户列表
public function index() {
$page = $_GET['page'] ?? 1;
$users = $this->userModel->getAll($page, 10);
// 渲染视图
$this->renderView('user/index', [
'users' => $users,
'currentPage' => $page
]);
}
// 显示用户详情
public function show($id) {
$user = $this->userModel->findById($id);
if (!$user) {
$this->redirect('/users');
return;
}
$this->renderView('user/show', ['user' => $user]);
}
// 创建用户表单
public function create() {
$this->renderView('user/create');
}
// 处理用户创建
public function store() {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
$this->redirect('/users/create');
return;
}
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
// 数据验证
$errors = [];
if (empty($username)) {
$errors[] = '用户名不能为空';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = '邮箱格式不正确';
}
if (strlen($password) userModel->create($username, $email, $password);
$this->redirect("/users/{$userId}");
return;
} catch (Exception $e) {
$errors[] = '创建用户失败: ' . $e->getMessage();
}
}
$this->renderView('user/create', [
'errors' => $errors,
'oldInput' => $_POST
]);
}
// 渲染视图
private function renderView($view, $data = []) {
extract($data);
require_once "app/views/{$view}.php";
}
// 重定向
private function redirect($url) {
header("Location: {$url}");
exit;
}
}
?>
视图模板示例
使用纯PHP模板语法创建可重用的视图组件。
用户列表视图
<!DOCTYPE html>
<html>
<head>
<title>用户管理系统</title>
<meta charset="UTF-8">
</head>
<body>
<div class="container">
<h1>用户列表</h1>
<?php if (!empty($users)): ?>
<table border="1" style="width: 100%; border-collapse: collapse;">
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>邮箱</th>
<th>注册时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user): ?>
<tr>
<td><?= htmlspecialchars($user['id']) ?></td>
<td><?= htmlspecialchars($user['username']) ?></td>
<td><?= htmlspecialchars($user['email']) ?></td>
<td><?= $user['created_at'] ?></td>
<td>
<a href="/users/<?= $user['id'] ?>" rel="external nofollow" >查看</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>暂无用户数据</p>
<?php endif; ?>
<div style="margin-top: 20px;">
<a href="/users/create" rel="external nofollow" >创建新用户</a>
</div>
</div>
</body>
</html>

