Z
ZHANK
进阶技巧

PHP 最佳实践

现代 PHP 编码规范、PSR 标准、安全编码、性能优化

PHP 最佳实践

现代 PHP 和十年前完全不同——类型系统、Composer 生态、PSR 规范让 PHP 工程化程度大幅提升。

学完本章你将: 掌握现代 PHP 编码规范、PSR 标准、安全编码。


现代 PHP 编码规范

php
<?php
declare(strict_types=1);  // 严格类型模式

namespace App\Services;

use App\Models\User;
use Psr\Log\LoggerInterface;

// ✅ 现代 PHP 风格
final class UserService {
    public function __construct(
        private readonly LoggerInterface $logger,
    ) { }

    public function findActiveUser(int $id): ?User {
        $this->logger->info("查找用户: $id");
        return User::find($id)?->isActive() ? User::find($id) : null;
    }
}

PSR 标准速查

标准内容
PSR-1基础编码规范
PSR-4自动加载规范
PSR-7HTTP 消息接口
PSR-12扩展编码风格(替代 PSR-2)
PSR-15HTTP 中间件

安全编码 Checklist

php
<?php
// ✅ 输出到 HTML
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// ✅ 数据库查询——永远用预处理
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(["id" => $id]);

// ✅ 密码哈希
$hash = password_hash($password, PASSWORD_BCRYPT);
if (password_verify($password, $hash)) { /* 密码正确 */ }

// ✅ CSRF 令牌
// ✅ 文件上传验证类型 + 大小
// ✅ 关闭错误显示(生产环境)
// ini_set('display_errors', '0');

性能优化建议

php
<?php
// 1. 使用 OpCache(生产环境必须开启)
// 2. Composer 生产模式:composer install --no-dev --optimize-autoloader
// 3. 数据库查询加索引、避免 N+1 问题
// 4. 使用缓存(Redis/Memcached)