本文目录导读:

我来给你梳理一个完整的 PHP 方案体系,从基础到高级应用:
核心架构方案
传统 MVA 架构
// 路由示例
// index.php
$controller = $_GET['c'] ?? 'Home';
$action = $_GET['a'] ?? 'index';
// 控制器
class HomeController {
public function index() {
$model = new UserModel();
$data = $model->getAll();
$this->view('home/index', $data);
}
}
// 模型
class UserModel {
public function getAll() {
return DB::table('users')->get();
}
}
现代 MVC 框架(推荐)
// Laravel 示例
Route::get('/users', [UserController::class, 'index']);
class UserController extends Controller {
public function index() {
$users = User::all();
return view('users.index', ['users' => $users]);
}
}
数据库方案
PDO 连接池
class Database {
private static $connections = [];
public static function getConnection() {
$key = 'main';
if (!isset(self::$connections[$key])) {
self::$connections[$key] = new PDO(
'mysql:host=localhost;dbname=test',
'user',
'password',
[
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
);
}
return self::$connections[$key];
}
}
// 查询示例
$stmt = Database::getConnection()->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
ORM 方案(Eloquent)
// 模型定义
class User extends Eloquent {
protected $table = 'users';
protected $fillable = ['name', 'email'];
public function orders() {
return $this->hasMany(Order::class);
}
}
// 链式查询
$users = User::where('status', 'active')
->orderBy('created_at', 'desc')
->paginate(10);
缓存方案
Redis 缓存
class Cache {
private static $redis;
public static function init() {
self::$redis = new Redis();
self::$redis->connect('127.0.0.1', 6379);
}
public static function get($key) {
$data = self::$redis->get($key);
return $data ? unserialize($data) : null;
}
public static function set($key, $value, $expire = 300) {
self::$redis->setex($key, $expire, serialize($value));
}
public static function remember($key, $expire, $callback) {
if ($data = self::get($key)) return $data;
$data = $callback();
self::set($key, $data, $expire);
return $data;
}
}
// 使用示例
$users = Cache::remember('users.all', 3600, function() {
return DB::table('users')->get();
});
安全防护方案
XSS 防护
function sanitize($data) {
return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
// 输出过滤
echo sanitize($userInput);
// Laravel 自带 Blade 模板自动转义
{{ $userInput }}
SQL 注入防护
// 参数化查询
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->bindParam(':email', $email);
$stmt->execute();
// Laravel 查询构造器
$users = DB::table('users')
->where('email', $email)
->get();
CSRF 防护
class Csrf {
public static function generate() {
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
return $token;
}
public static function verify($token) {
return hash_equals($_SESSION['csrf_token'] ?? '', $token);
}
}
性能优化方案
OPcache 配置
[opcache] opcache.enable=1 opcache.memory_consumption=128 opcache.interned_strings_buffer=8 opcache.max_accelerated_files=10000 opcache.revalidate_freq=2 opcache.enable_cli=0
异步任务处理
// 队列(Redis 队列)
class Queue {
public static function push($job, $data) {
$job = new \RedisQueue\Job($job, $data);
return Redis::lpush('queue:jobs', serialize($job));
}
public static function pop() {
$data = Redis::rpop('queue:jobs');
return $data ? unserialize($data) : null;
}
}
文件上传方案
class Uploader {
public static function upload($file, $dir = 'uploads') {
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('上传失败');
}
// 验证类型和大小
$allowed = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($file['type'], $allowed)) {
throw new Exception('文件类型不允许');
}
if ($file['size'] > 2 * 1024 * 1024) {
throw new Exception('文件过大');
}
// 生成唯一文件名
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = date('Ymd') . '/' . uniqid() . '.' . $ext;
$target = $dir . '/' . $filename;
move_uploaded_file($file['tmp_name'], $target);
return ['success' => true, 'path' => $filename];
}
}
API 开发方案
class ApiController {
protected function success($data, $message = 'ok') {
return json_encode([
'code' => 200,
'message' => $message,
'data' => $data
]);
}
protected function error($message, $code = 500) {
return json_encode([
'code' => $code,
'message' => $message,
'data' => null
]);
}
}
// 接口验证
class ApiAuth {
public static function verify($request) {
$token = $request->header('Authorization');
// JWT 验证或 Token 验证
}
}
测试方案
// PHPUnit 单元测试
class UserTest extends PHPUnit\Framework\TestCase {
public function testCreateUser() {
$user = new User();
$user->name = 'Test';
$user->email = 'test@example.com';
$saved = $user->save();
$this->assertTrue($saved);
$this->assertNotNull($user->id);
$this->assertInstanceOf(User::class, User::find($user->id));
}
}
// Laravel 集成测试
class TaskTest extends TestCase {
public function test_task_can_be_created() {
$response = $this->post('/tasks', [
'title' => 'Sample task'
]);
$response->assertStatus(201);
$response->assertJson(['title' => 'Sample task']);
}
}
部署方案
Docker 容器化
FROM php:8.2-fpm RUN docker-php-ext-install pdo_mysql opcache # 安装 Redis 扩展 RUN pecl install redis && docker-php-ext-enable redis COPY . /var/www/html WORKDIR /var/www/html EXPOSE 9000
CI/CD 配置
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
- name: Install dependencies
run: composer install
- name: Run tests
run: php artisan test
- name: Deploy
run: ./deploy.sh
日志与监控
class Logger {
public static function info($message, $context = []) {
self::writeLog('INFO', $message, $context);
}
public static function error($message, $context = []) {
self::writeLog('ERROR', $message, $context);
}
private static function writeLog($level, $message, $context) {
$log = sprintf(
"[%s] [%s] %s %s\n",
date('Y-m-d H:i:s'),
$level,
$message,
json_encode($context, JSON_UNESCAPED_UNICODE)
);
file_put_contents(
storage_path() . '/logs/' . date('Y-m-d') . '.log',
$log,
FILE_APPEND
);
}
}
推荐技术栈组合
| 场景 | 推荐方案 |
|---|---|
| 小型项目 | 原生 PHP + PDO + MySQL |
| 中型项目 | Laravel 6/8/9/10 + Redis + Vue |
| API 开发 | Laravel + Sanctum + Swagger |
| 微服务 | Lumen/Slim + API Gateway |
| 高并发 | Swoole + Redis + 负载均衡 |
- 版本控制:Git + GitFlow 分支策略
- 代码标准:PSR-4 自动加载 + PSR-12 编码规范
- 自动测试:单元测试覆盖率 80%+
- 错误处理:全局异常捕获 + 优雅降级
- 安全防护:输入验证 + CSRF + XSS 防护
- 性能考虑:缓存优化 + 数据库索引 + 查询优化
- 监控告警:日志记录 + 性能监控 + 错误追踪
这个方案体系覆盖了 PHP 开发的大部分场景,你可以根据项目规模选择适合的组合,需要深入了解某个特定部分吗?