适用人群:学完基础想做项目的开发者
学习时长:每个项目1-2周
包含语言:PHP/Python/Go/Java/Node.js
项目类型:博客系统、电商后台、API服务
一、项目1:用户管理系统(CRUD + 认证)
1.1 功能清单
✅ 用户注册(邮箱验证)
✅ 用户登录(JWT认证)
✅ 用户列表(分页、搜索)
✅ 用户详情
✅ 用户编辑
✅ 用户删除
✅ 密码重置
✅ 个人资料修改
1.2 数据库设计
-- 用户表
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
nickname VARCHAR(50),
avatar VARCHAR(255),
phone VARCHAR(20),
role ENUM('admin', 'editor', 'user') DEFAULT 'user',
is_active BOOLEAN DEFAULT TRUE,
last_login_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_email (email),
INDEX idx_role (role),
INDEX idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 用户Token表(可选,用于Token黑名单)
CREATE TABLE user_tokens (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
token VARCHAR(500) NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_token (token(100)),
INDEX idx_expires (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
1.3 API设计
POST /api/auth/register # 注册
POST /api/auth/login # 登录
POST /api/auth/logout # 退出
GET /api/auth/me # 获取当前用户
GET /api/users # 用户列表(需认证)
GET /api/users/:id # 用户详情(需认证)
POST /api/users # 创建用户(需管理员)
PUT /api/users/:id # 更新用户(需认证)
DELETE /api/users/:id # 删除用户(需管理员)
PUT /api/users/:id/password # 修改密码
POST /api/auth/forgot-password # 忘记密码
POST /api/auth/reset-password # 重置密码
1.4 PHP Laravel 实现
// routes/api.php
Route::post('/auth/register', [AuthController::class, 'register']);
Route::post('/auth/login', [AuthController::class, 'login']);
Route::middleware('auth:sanctum')->group(function () {
Route::get('/auth/me', [AuthController::class, 'me']);
Route::post('/auth/logout', [AuthController::class, 'logout']);
Route::apiResource('users', UserController::class);
});
// app/Http/Controllers/AuthController.php
class AuthController extends Controller
{
public function register(Request $request)
{
$validated = $request->validate([
'username' => 'required|string|min:3|max:50|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:8|confirmed',
]);
$user = User::create([
'username' => $validated['username'],
'email' => $validated['email'],
'password' => Hash::make($validated['password']),
]);
$token = $user->createToken('auth-token')->plainToken;
return response()->json([
'code' => 201,
'message' => '注册成功',
'data' => [
'user' => $user,
'token' => $token,
]
], 201);
}
public function login(Request $request)
{
$request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (!Auth::attempt($request->only('email', 'password'))) {
return response()->json([
'code' => 401,
'message' => '邮箱或密码错误'
], 401);
}
$user = User::where('email', $request->email)->first();
$token = $user->createToken('auth-token')->plainToken;
return response()->json([
'code' => 200,
'message' => '登录成功',
'data' => [
'user' => $user,
'token' => $token,
]
]);
}
public function me(Request $request)
{
return response()->json([
'code' => 200,
'data' => $request->user()
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->json(['code' => 200, 'message' => '已退出']);
}
}
1.5 Python Flask 实现
# app.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import timedelta
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
app.config['JWT_SECRET_KEY'] = 'your-secret-key'
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)
db = SQLAlchemy(app)
jwt = JWTManager(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50), unique=True, nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=False)
role = db.Column(db.String(20), default='user')
is_active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def to_dict(self):
return {
'id': self.id,
'username': self.username,
'email': self.email,
'role': self.role,
'is_active': self.is_active
}
@app.route('/api/auth/register', methods=['POST'])
def register():
data = request.get_json()
if User.query.filter_by(username=data['username']).first():
return jsonify({'code': 409, 'message': '用户名已存在'}), 409
user = User(
username=data['username'],
email=data['email'],
password_hash=generate_password_hash(data['password'])
)
db.session.add(user)
db.session.commit()
token = create_access_token(identity=user.id)
return jsonify({
'code': 201,
'data': {'user': user.to_dict(), 'token': token}
}), 201
@app.route('/api/auth/login', methods=['POST'])
def login():
data = request.get_json()
user = User.query.filter_by(email=data['email']).first()
if not user or not check_password_hash(user.password_hash, data['password']):
return jsonify({'code': 401, 'message': '邮箱或密码错误'}), 401
token = create_access_token(identity=user.id)
return jsonify({
'code': 200,
'data': {'user': user.to_dict(), 'token': token}
})
@app.route('/api/users', methods=['GET'])
@jwt_required()
def get_users():
page = request.args.get('page', 1, type=int)
size = request.args.get('size', 10, type=int)
pagination = User.query.paginate(page=page, per_page=size)
return jsonify({
'code': 200,
'data': {
'items': [u.to_dict() for u in pagination.items],
'total': pagination.total,
'page': page,
'size': size
}
})
二、项目2:博客系统
2.1 功能清单
✅ 文章CRUD
✅ 分类管理
✅ 标签管理
✅ 评论系统
✅ 文章搜索
✅ 文章归档
✅ RSS订阅
✅ Markdown渲染
2.2 数据库设计
-- 文章表
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
slug VARCHAR(200) NOT NULL UNIQUE,
content TEXT NOT NULL,
excerpt VARCHAR(500),
cover_image VARCHAR(255),
status ENUM('draft', 'published', 'archived') DEFAULT 'draft',
views INT DEFAULT 0,
author_id INT NOT NULL,
category_id INT,
published_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (author_id) REFERENCES users(id),
FOREIGN KEY (category_id) REFERENCES categories(id),
INDEX idx_slug (slug),
INDEX idx_status (status),
INDEX idx_published_at (published_at),
FULLTEXT INDEX ft_title_content (title, content)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 分类表
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE,
slug VARCHAR(50) NOT NULL UNIQUE,
description VARCHAR(200),
sort_order INT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 标签表
CREATE TABLE tags (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL UNIQUE,
slug VARCHAR(50) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 文章标签关联表
CREATE TABLE post_tags (
post_id INT NOT NULL,
tag_id INT NOT NULL,
PRIMARY KEY (post_id, tag_id),
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 评论表
CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT,
parent_id INT,
content TEXT NOT NULL,
status ENUM('pending', 'approved', 'rejected') DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL,
FOREIGN KEY (parent_id) REFERENCES comments(id) ON DELETE CASCADE,
INDEX idx_post_status (post_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
2.3 API设计
# 文章
GET /api/posts # 文章列表
GET /api/posts/:slug # 文章详情(通过slug)
POST /api/posts # 创建文章(需认证)
PUT /api/posts/:id # 更新文章(需认证)
DELETE /api/posts/:id # 删除文章(需认证)
# 分类
GET /api/categories # 分类列表
POST /api/categories # 创建分类(需管理员)
# 标签
GET /api/tags # 标签列表
# 评论
GET /api/posts/:id/comments # 文章评论
POST /api/posts/:id/comments # 添加评论
# 搜索
GET /api/search?q=keyword # 全文搜索
三、项目3:电商后台API
3.1 功能清单
✅ 商品管理(CRUD、图片上传、库存管理)
✅ 商品分类
✅ 订单管理(创建、支付、发货、完成)
✅ 购物车
✅ 用户地址管理
✅ 支付集成(支付宝/微信)
✅ 数据统计
3.2 数据库设计
-- 商品表
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(200) NOT NULL,
slug VARCHAR(200) NOT NULL UNIQUE,
description TEXT,
price DECIMAL(10, 2) NOT NULL,
original_price DECIMAL(10, 2),
stock INT NOT NULL DEFAULT 0,
sales INT DEFAULT 0,
category_id INT,
cover_image VARCHAR(255),
images JSON,
status ENUM('on_sale', 'off_sale', 'sold_out') DEFAULT 'on_sale',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(id),
INDEX idx_category (category_id),
INDEX idx_status (status),
INDEX idx_price (price),
FULLTEXT INDEX ft_name_desc (name, description)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单表
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
order_no VARCHAR(32) NOT NULL UNIQUE,
user_id INT NOT NULL,
total_amount DECIMAL(10, 2) NOT NULL,
status ENUM('pending', 'paid', 'shipped', 'completed', 'cancelled') DEFAULT 'pending',
address_snapshot JSON NOT NULL,
payment_method VARCHAR(20),
payment_no VARCHAR(64),
paid_at TIMESTAMP NULL,
shipped_at TIMESTAMP NULL,
completed_at TIMESTAMP NULL,
remark VARCHAR(500),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
INDEX idx_order_no (order_no),
INDEX idx_user_status (user_id, status),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单商品表
CREATE TABLE order_items (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
product_name VARCHAR(200) NOT NULL,
product_image VARCHAR(255),
price DECIMAL(10, 2) NOT NULL,
quantity INT NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id),
INDEX idx_order (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 购物车表
CREATE TABLE cart_items (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
UNIQUE KEY uk_user_product (user_id, product_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
四、项目4:实时聊天应用
4.1 技术栈
前端:Vue 3 + Socket.io-client
后端:Node.js + Express + Socket.io
数据库:MongoDB + Redis
部署:Docker + Nginx
4.2 核心功能
✅ 单聊
✅ 群聊
✅ 消息已读
✅ 在线状态
✅ 文件发送
✅ 消息历史
4.3 Socket.io 实现
// server.js
import { Server } from 'socket.io'
import jwt from 'jsonwebtoken'
const io = new Server(server, {
cors: { origin: '*' }
})
// 认证中间件
io.use((socket, next) => {
const token = socket.handshake.auth.token
try {
const decoded = jwt.verify(token, SECRET_KEY)
socket.userId = decoded.userId
next()
} catch (err) {
next(new Error('认证失败'))
}
})
io.on('connection', (socket) => {
console.log(`用户 ${socket.userId} 已连接`)
// 加入用户自己的房间
socket.join(`user:${socket.userId}`)
// 私聊
socket.on('private-message', async ({ to, content }) => {
const message = {
from: socket.userId,
to,
content,
timestamp: new Date()
}
// 保存到数据库
await saveMessage(message)
// 发送给接收者
io.to(`user:${to}`).emit('new-message', message)
// 发送回执给发送者
socket.emit('message-sent', { id: message.id, status: 'sent' })
})
// 群聊
socket.on('group-message', async ({ groupId, content }) => {
const message = {
from: socket.userId,
groupId,
content,
timestamp: new Date()
}
await saveMessage(message)
io.to(`group:${groupId}`).emit('new-message', message)
})
// 加入群组
socket.on('join-group', (groupId) => {
socket.join(`group:${groupId}`)
})
// 输入状态
socket.on('typing', ({ to }) => {
io.to(`user:${to}`).emit('user-typing', { userId: socket.userId })
})
// 断开连接
socket.on('disconnect', () => {
console.log(`用户 ${socket.userId} 已断开`)
})
})
五、项目部署检查清单
# 代码准备
✅ 删除console.log和调试代码
✅ 环境变量配置(.env.production)
✅ 错误处理完善
✅ 输入验证完善
✅ SQL注入防护
✅ XSS防护
✅ CORS配置
# 数据库
✅ 创建生产数据库
✅ 执行迁移
✅ 创建索引
✅ 配置备份
# 服务器
✅ Nginx配置
✅ SSL证书
✅ 防火墙配置
✅ 进程管理(PM2/Supervisor)
✅ 日志配置
# 监控
✅ 错误监控(Sentry)
✅ 性能监控
✅ 服务器监控
✅ 数据库监控
# CI/CD
✅ Git仓库
✅ 自动部署脚本
✅ 回滚方案
学习建议
- 先做用户管理系统,掌握CRUD和认证
- 再做博客系统,学习内容管理和搜索
- 然后做电商后台,理解复杂业务逻辑
- 最后做实时应用,学习WebSocket
- 每个项目都要部署上线,积累实战经验
下一步学习