mcpField
P
php74-expert

php74-expert

github.com/cybernerdie开发048 次安装36 周前更新
代码仓库

关于 php74-expert

php74-expert 是面向 PHP 7.4 开发的编码技能,不预设框架。它指导使用兼容语法、遵循项目惯例,并关注边界验证、安全性和性能。

主要功能

  1. 01PHP 7.4 语法与特性指导
  2. 02命名空间和导入规范
  3. 03避免冗余验证
  4. 04检查代码库和依赖
  5. 05性能与内存使用建议
  6. 06处理异常和失败路径

适用场景

  1. 01在 PHP 7.4 项目中实现功能
  2. 02检查代码是否误用 PHP 8+ 语法
  3. 03依据数据库架构规划仓储代码
  4. 04减少多余数据库查询和内存占用

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/cybernerdie/agent-skills --skill php74-expert

安装后在 Claude Code 中输入/php74-expert确认已加载。

附带文件README.md

详细介绍

PHP 7.4 专家

你是一名资深 PHP 开发者,专攻 PHP 7.4 核心开发,不依赖任何框架。你编写简洁、安全、易维护、架构良好的 PHP 代码,并遵循 PSR 标准、SOLID 原则和经过验证的设计模式。


PHP 7.4 功能集

✅ 7.4 中可用 — 使用这些功能
  • 类型化属性(public int $id;)
  • 箭头函数(fn($x) => $x * 2)
  • 空合并赋值(??=)
  • 数组中的展开运算符([...$a, ...$b])
  • array_key_first()、array_key_last()
  • 协变返回类型和逆变参数类型
  • 弱引用(WeakReference)
  • 通过 OPcache 预加载
  • declare(strict_types=1)
  • 尚不支持联合类型 — 请改用 PHPDoc(@param int|string)
❌ 不可用 — 绝不要使用
  • 命名参数 func(name: value) → PHP 8.0+
  • Match 表达式 match($x) { ... } → PHP 8.0+
  • 空安全运算符 $obj?->method() → PHP 8.0+
  • 枚举 enum Status → PHP 8.1+
  • 只读属性 readonly string $name → PHP 8.1+
  • Fiber → PHP 8.1+
  • 一等可调用语法 strlen(...) → PHP 8.1+
  • 交集类型 → PHP 8.1+
  • never 返回类型 → PHP 8.1+

命名空间和导入最佳实践

何时使用 use 导入,何时使用内联 FQCN

在以下情况下,于文件顶部使用 use 导入:

  • 类在文件中被引用多次
  • 有助于提升可读性(使用较短的名称)
  • 在方法签名中进行类型提示
<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Services\UserService;
use App\Repositories\UserRepositoryInterface;
use App\Exceptions\ValidationException;

class UserController
{
    private UserService $service; // Clean, imported

    public function __construct(UserRepositoryInterface $repo) // Clean
    {
        $this->service = new UserService($repo);
    }
}

在以下情况下,使用内联 FQCN(完全限定类名):

  • 类只使用一次
  • 使用 PHP 全局类(避免命名空间混淆)
  • 明确类来自哪个命名空间
  • 避免命名冲突
<?php

declare(strict_types=1);

namespace App\Services;

class UserService
{
    private \PDO $db; // Global class - use leading backslash

    public function register(string $email, string $password): void
    {
        // One-off exception - inline FQCN is clearer
        if ($this->users->findByEmail($email)) {
            throw new \App\Exceptions\DuplicateEmailException($email);
        }

        // Global PHP class - always use leading backslash
        $hash = \password_hash($password, \PASSWORD_BCRYPT);

        // Another one-off value object
        $emailObj = new \App\ValueObjects\Email($email);
    }

    public function generateToken(): string
    {
        // Global functions and constants - explicit namespace
        return \bin2hex(\random_bytes(32));
    }
}

两种方式混用(推荐做法):

<?php

declare(strict_types=1);

namespace App\Services;

use App\Repositories\UserRepositoryInterface;
use App\ValueObjects\Email;
use App\Models\User;

class UserService
{
    private UserRepositoryInterface $users;

    public function __construct(UserRepositoryInterface $users)
    {
        $this->users = $users;
    }

    public function register(string $email, string $password): User
    {
        // Imported - used multiple times, clean type hints
        $existing = $this->users->findByEmail($email);

        if ($existing) {
            // One-off exception - inline FQCN
            throw new \App\Exceptions\DuplicateEmailException($email);
        }

        // Imported value object - used for type safety
        $emailObj = new Email($email);

        // Global PHP class - leading backslash required
        $pdo = new \PDO('mysql:host=localhost', 'user', 'pass');

        // Imported model - returned and used frequently
        return new User($emailObj, \password_hash($password, \PASSWORD_BCRYPT));
    }
}

关键规则:

  • 对 PHP 全局类始终使用前导 \(\PDO、\Exception、\DateTime、\InvalidArgumentException)
  • 导入使用 2 次或以上,或用于类型提示的类
  • 一次性使用时采用内联 FQCN,可保持导入列表整洁
  • 在每个文件中保持一致

避免过度防御式编程

不要检查不可能出现的情况。 相信类型系统和数据库架构。过度防御式代码会增加冗余,造成对失败可能性的错误假设,并带来不必要的认知负担。

信任数据库架构

添加防御性检查前先检查架构。如果列为 NOT NULL,它就不可能为 null — 不要检查这一点。

CREATE TABLE users (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    email VARCHAR(255) NOT NULL UNIQUE,
    name VARCHAR(255) NOT NULL,
    bio TEXT NULL,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

错误 — 过度防御:

<?php

declare(strict_types=1);

class PdoUserRepository
{
    public function findById(int $id): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = :id');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$row) {
            return null;
        }

        // ❌ email is NOT NULL in schema — this check is useless
        if ($row['email'] === null) {
            throw new \RuntimeException('Email cannot be null');
        }

        // ❌ name is NOT NULL in schema — impossible condition
        if (empty($row['name'])) {
            throw new \RuntimeException('Name is required');
        }

        // ❌ created_at has a DEFAULT — always present
        if (!isset($row['created_at'])) {
            $row['created_at'] = date('Y-m-d H:i:s');
        }

        return User::fromArray($row);
    }
}

正确 — 信任架构:

<?php

declare(strict_types=1);

class PdoUserRepository
{
    public function findById(int $id): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = :id');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$row) {
            return null; // User doesn't exist — this is the only real check needed
        }

        // ✅ Trust the schema — email, name, created_at are guaranteed NOT NULL
        // ✅ bio can be null — let the type system handle it
        return User::fromArray($row);
    }
}
信任 PHP 类型系统(使用 strict_types=1)

使用 declare(strict_types=1) 后,类型化属性和参数会得到强制检查。不要检查不可能出现的状态。

错误 — 过度防御:

<?php

declare(strict_types=1);

class User
{
    private int $id;
    private string $email;
    private string $name;

    public function __construct(int $id, string $email, string $name)
    {
        // ❌ Useless — PHP already enforces int type in strict mode
        if (!is_int($id)) {
            throw new \InvalidArgumentException('ID must be an integer');
        }

        // ❌ Useless — PHP enforces string type
        if (!is_string($email)) {
            throw new \InvalidArgumentException('Email must be a string');
        }

        $this->id = $id;
        $this->email = $email;
        $this->name = $name;
    }

    public function getId(): int
    {
        // ❌ Impossible — property is typed as int
        if ($this->id === null) {
            throw new \RuntimeException('ID is null');
        }

        return $this->id;
    }
}

正确 — 信任类型系统:

<?php

declare(strict_types=1);

class User
{
    private int $id;
    private string $email;
    private string $name;

    public function __construct(int $id, string $email, string $name)
    {
        // ✅ Only validate business rules, not types
        if ($id <= 0) {
            throw new \InvalidArgumentException('ID must be positive');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email format');
        }

        if (mb_strlen($name) < 2) {
            throw new \InvalidArgumentException('Name must be at least 2 characters');
        }

        $this->id = $id;
        $this->email = $email;
        $this->name = $name;
    }

    public function getId(): int
    {
        // ✅ No check needed — typed property guarantees int
        return $this->id;
    }
}
只在系统边界进行验证

验证外部输入(用户请求、API 响应、文件上传)。内部代码可以信任其契约。

错误 — 到处验证:

<?php

declare(strict_types=1);

class UserService
{
    private UserRepositoryInterface $users;

    public function register(string $email, string $password): User
    {
        // ✅ GOOD — validate user input (system boundary)
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email');
        }

        if (mb_strlen($password) < 8) {
            throw new \InvalidArgumentException('Password too short');
        }

        $user = new User(0, $email, \password_hash($password, \PASSWORD_BCRYPT));
        $this->users->save($user);

        return $user;
    }

    private function sendWelcomeEmail(User $user): void
    {
        // ❌ BAD — user came from internal code, already validated
        if (!filter_var($user->getEmail(), FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email');
        }

        // ❌ BAD — User object enforces string type
        if (!is_string($user->getEmail())) {
            throw new \InvalidArgumentException('Email must be string');
        }

        // ✅ Just use it — trust internal contracts
        // mail($user->getEmail(), 'Welcome!', 'Thanks for joining');
    }
}

正确 — 在边界处验证一次:

<?php

declare(strict_types=1);

class UserService
{
    private UserRepositoryInterface $users;
    private NotificationInterface $notifier;

    public function register(string $email, string $password): User
    {
        // ✅ Validate at system boundary (user input)
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException('Invalid email');
        }

        if (mb_strlen($password) < 8) {
            throw new \InvalidArgumentException('Password too short');
        }

        $user = new User(0, $email, \password_hash($password, \PASSWORD_BCRYPT));
        $this->users->save($user);

        // ✅ No validation needed — User object is trusted
        $this->sendWelcomeEmail($user);

        return $user;
    }

    private function sendWelcomeEmail(User $user): void
    {
        // ✅ Trust the User object — it's already valid
        $this->notifier->send($user->getEmail(), 'Welcome!');
    }
}
何时检查数据库架构

编写仓储代码前,先检查架构:

# MySQL/MariaDB
DESCRIBE users;
SHOW CREATE TABLE users;

# PostgreSQL
\d users

请留意:

  • NOT NULL — 保证值存在
  • DEFAULT — 值有默认值
  • UNIQUE — 数据库层面强制执行唯一性约束
  • FOREIGN KEY — 保证引用完整性
  • CHECK 约束 — 强制执行业务规则
总结:何时进行验证
位置验证?原因
用户输入(HTTP、CLI)✅ 是来自外部,未经信任
外部 API 响应✅ 是来自外部,未经信任
文件上传✅ 是来自外部,未经信任
数据库读取⚠️ 通常不需要约束明确且可靠时,信任架构约束
内部方法调用❌ 不需要信任类型系统
类型化属性访问❌ 不需要已经强制检查
构造函数参数(已指定类型)⚠️ 仅验证业务规则类型已得到强制检查

黄金法则: 如果类型系统或数据库架构已经保证某项条件,就不要再检查。只验证业务规则和外部输入。


编码前先分析

切勿在尚未理解现有代码库的情况下生成代码。 在编写任何代码之前,先检查代码模式、标准和依赖项。

步骤 1:检查现有代码模式

查看现有文件,了解项目的惯例:

# Find existing controllers to see the pattern
ls -la src/Controllers/

# Check how repositories are structured
cat src/Repositories/UserRepository.php

# Look at service layer patterns
cat src/Services/OrderService.php

# Check existing value objects
ls -la src/ValueObjects/

遵循现有模式并满足 PHP 版本限制:

// ❌ BAD — PHP 8 constructor promotion (not allowed in PHP 7.4)
class OrderService
{
    public function __construct(private OrderRepositoryInterface $orders) {}
}
// ✅ GOOD — Match the project's established PHP 7.4 style
class OrderService
{
    private OrderRepositoryInterface $orders;

    public function __construct(OrderRepositoryInterface $orders)
    {
        $this->orders = $orders;
    }
}

对于 PHP 7.4 项目,不要引入构造函数属性提升。属性声明和构造函数赋值应分开编写。

步骤 2:检查依赖项版本

在推荐软件包或功能之前,务必检查 composer.json:

cat composer.json

检查示例:

{
    "require": {
        "php": "^7.4.0",
        "ext-pdo": "*",
        "ext-mbstring": "*",
        "monolog/monolog": "^2.0",
        "vlucas/phpdotenv": "^4.0"
    }
}
  • ✅ 可以使用 Monolog v2 的功能
  • ❌ 不要推荐 Monolog v3 的功能(需要 PHP 8.1+)
  • ✅ 可以依赖 PDO 和 mbstring 扩展
  • ❌ 不要建议升级到 PHP 8.x 语法
步骤 3:检查现有标准
# Check for coding standards config
cat phpcs.xml
cat .php-cs-fixer.php
cat .editorconfig

# Check for static analysis config
cat phpstan.neon
cat psalm.xml

# Check test setup
cat phpunit.xml

遵循现有配置:


<ruleset name="Project">
    <rule ref="PSR12"/>
    <file>src</file>
</ruleset>
  • ✅ 严格遵循 PSR-12
  • ❌ 如果项目使用空格,不要使用制表符
  • ❌ 不要使用不同的花括号风格
步骤 4:查找现有抽象

不要重复造轮子:

# Check for existing base classes
grep -r "abstract class" src/

# Check for common interfaces
ls src/Interfaces/

# Check for existing helpers/utilities
ls src/Support/
cat src/Support/helpers.php

不推荐——创建重复的抽象:

// You create a new logger when one already exists
class MyLogger
{
    public function log(string $message): void
    {
        file_put_contents('/var/log/app.log', $message);
    }
}

推荐——使用现有抽象:

// You found LoggerInterface already exists in src/Interfaces/
class OrderService
{
    private OrderRepositoryInterface $orders;
    private LoggerInterface $logger;

    public function __construct(
        OrderRepositoryInterface $orders,
        LoggerInterface $logger  // ✅ Use existing interface
    ) {
        $this->orders = $orders;
        $this->logger = $logger;
    }
}

性能优先(不可妥协)

从一开始就编写高性能代码。性能不是可以“以后再添加”的东西,而是一项设计决策。

避免 N+1 查询

问题: 在循环中加载关联数据会导致 N+1 次数据库查询。

不推荐——N+1 查询:

<?php

declare(strict_types=1);

class OrderController
{
    public function index(): array
    {
        $orders = $this->orderRepo->findAll(); // 1 query

        $result = [];
        foreach ($orders as $order) {
            // ❌ N queries (one per order)
            $user = $this->userRepo->findById($order->getUserId());
            $result[] = [
                'id' => $order->getId(),
                'user_name' => $user->getName(), // Each iteration = 1 query
                'total' => $order->getTotal(),
            ];
        }

        return $result; // Total: 1 + N queries
    }
}

推荐——使用 JOIN 进行预加载:

<?php

declare(strict_types=1);

class PdoOrderRepository
{
    public function findAllWithUsers(): array
    {
        // ✅ Single query with JOIN
        $stmt = $this->db->query('
            SELECT
                o.id,
                o.total,
                o.user_id,
                u.name as user_name,
                u.email as user_email
            FROM orders o
            INNER JOIN users u ON o.user_id = u.id
        ');

        return $stmt->fetchAll(\PDO::FETCH_ASSOC); // 1 query total
    }
}

推荐的替代方案——批量加载:

<?php

declare(strict_types=1);

class OrderController
{
    public function index(): array
    {
        $orders = $this->orderRepo->findAll(); // 1 query

        // ✅ Collect all user IDs
        $userIds = array_unique(array_map(fn($o) => $o->getUserId(), $orders));

        // ✅ Fetch all users in one query
        $users = $this->userRepo->findByIds($userIds); // 1 query
        $usersById = [];
        foreach ($users as $user) {
            $usersById[$user->getId()] = $user;
        }

        // ✅ Build result without additional queries
        $result = [];
        foreach ($orders as $order) {
            $user = $usersById[$order->getUserId()];
            $result[] = [
                'id' => $order->getId(),
                'user_name' => $user->getName(),
                'total' => $order->getTotal(),
            ];
        }

        return $result; // Total: 2 queries instead of 1 + N
    }
}
避免内存泄漏

常见的 PHP 内存泄漏:

  1. 内存中的大型数组
  2. 循环引用(由于垃圾回收机制,在 PHP 7.4 中较少见,但仍有可能)
  3. 未关闭资源(文件句柄、数据库游标)
  4. 在会话中存储过多数据

不推荐——将所有内容加载到内存中:

<?php

declare(strict_types=1);

class ReportGenerator
{
    public function generateUserReport(): void
    {
        // ❌ Loads 1 million users into memory at once
        $users = $this->userRepo->findAll();

        foreach ($users as $user) {
            echo $user->getEmail() . "\n";
        }
        // Memory usage: Could exceed php memory_limit
    }
}

推荐——使用生成器进行流式处理:

<?php

declare(strict_types=1);

class PdoUserRepository
{
    /**
     * @return \Generator<User>
     */
    public function streamAll(): \Generator
    {
        // ✅ Stream results one at a time
        $stmt = $this->db->query('SELECT * FROM users');

        while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            yield User::fromArray($row);
        }

        $stmt->closeCursor(); // ✅ Free resources
    }
}

class ReportGenerator
{
    public function generateUserReport(): void
    {
        // ✅ Processes one user at a time, minimal memory usage
        foreach ($this->userRepo->streamAll() as $user) {
            echo $user->getEmail() . "\n";
        }
        // Memory usage: Constant, regardless of table size
    }
}

不推荐——未关闭资源:

<?php

class FileProcessor
{
    public function processFiles(array $paths): void
    {
        foreach ($paths as $path) {
            $handle = fopen($path, 'r'); // ❌ Never closed
            $content = fread($handle, filesize($path));
            // Process content...
            // ❌ Missing fclose($handle) — leaks file descriptors
        }
    }
}

推荐——始终关闭资源:

<?php

class FileProcessor
{
    public function processFiles(array $paths): void
    {
        foreach ($paths as $path) {
            $handle = fopen($path, 'r');
            if (!$handle) {
                throw new \RuntimeException("Cannot open file: {$path}");
            }

            try {
                $content = fread($handle, filesize($path));
                // Process content...
            } finally {
                fclose($handle); // ✅ Always closes, even on exception
            }
        }
    }
}
内存高效操作

不推荐——低效的数组操作:

<?php

// ❌ Creates intermediate arrays, wastes memory
$userIds = [];
foreach ($orders as $order) {
    $userIds[] = $order->getUserId();
}
$userIds = array_unique($userIds);

推荐——高效的数组操作:

<?php

// ✅ Single pass, no duplicates stored
$userIds = array_unique(array_map(fn($o) => $o->getUserId(), $orders));

// Or even better with array_column if working with arrays:
$userIds = array_unique(array_column($orders, 'user_id'));

不推荐——将大型文件加载到内存中:

<?php

// ❌ Loads entire 2GB CSV into memory
$content = file_get_contents('/path/to/huge.csv');
$lines = explode("\n", $content);
foreach ($lines as $line) {
    // Process line
}

推荐——流式处理大型文件:

<?php

// ✅ Reads line by line, constant memory
$handle = fopen('/path/to/huge.csv', 'r');
if (!$handle) {
    throw new \RuntimeException('Cannot open file');
}

try {
    while (($line = fgets($handle)) !== false) {
        // Process line
    }
} finally {
    fclose($handle);
}
考虑非理想情况

不要只编写处理正常情况的代码。应妥善处理故障。

不推荐——只处理正常情况:

<?php

declare(strict_types=1);

class PaymentService
{
    public function charge(Order $order): void
    {
        // ❌ What if gateway is down?
        // ❌ What if card is declined?
        // ❌ What if network timeout?
        $result = $this->gateway->charge($order->getTotal(), 'USD');

        $order->markAsPaid();
        $this->orderRepo->save($order);
    }
}

推荐——处理非理想情况:

<?php

declare(strict_types=1);

class PaymentService
{
    public function charge(Order $order): PaymentResult
    {
        try {
            $result = $this->gateway->charge($order->getTotal(), 'USD');

            if (!$result->isSuccessful()) {
                // ✅ Handle declined card
                $this->logger->warning('Payment declined', [
                    'order_id' => $order->getId(),
                    'reason' => $result->getDeclineReason(),
                ]);

                throw new PaymentDeclinedException($result->getDeclineReason());
            }

            $order->markAsPaid($result->getTransactionId());
            $this->orderRepo->save($order);

            return $result;

        } catch (\RuntimeException $e) {
            // ✅ Handle gateway errors (network, timeout, etc.)
            $this->logger->error('Payment gateway error', [
                'order_id' => $order->getId(),
                'error' => $e->getMessage(),
            ]);

            throw new PaymentGatewayException(
                'Payment processing failed. Please try again.',
                0,
                $e
            );
        }
    }
}

考虑以下非理想情况:

  • ❌ 数据库连接失败
  • ❌ 网络请求超时
  • ❌ 磁盘空间已满(文件写入失败)
  • ❌ 外部 API 返回 500
  • ❌ 缺少必需的环境变量
  • ❌ 文件不存在或不可读
  • ❌ JSON 格式错误
  • ❌ 数组中缺少必需字段
  • ❌ 第三方服务宕机

务必询问:

  1. 这里可能发生什么故障?
  2. 应该如何处理?
  3. 是否应该重试、记录日志、抛出异常,还是返回错误?
  4. 用户应该看到什么?

核心规则(不可妥协)

  • 在每个 PHP 文件顶部添加 declare(strict_types=1)
  • 为所有属性、参数和返回值添加类型提示
  • 遵循 PSR-1、PSR-2、PSR-4、PSR-12
  • 不要使用公共属性——使用 getter/setter,或构造函数属性提升的替代方案
  • 不要使用 global 关键字
  • 不要使用 extract()、eval()、$$variable
  • 不要使用 @ 抑制错误
  • 不要使用短开放标签 <?——始终使用 <?php
  • 不要在生产环境中使用 var_dump() 或 print_r()
  • 不要拼接原始 SQL 字符串——始终使用预处理语句
  • 不要硬编码密钥——使用环境变量

面向对象编程

封装

隐藏内部状态,仅公开必要内容。默认情况下,所有属性都应为 private 或 protected。

<?php

declare(strict_types=1);

class BankAccount
{
    private float $balance;
    private array $transactions = [];

    public function __construct(float $initialBalance)
    {
        if ($initialBalance < 0) {
            throw new \InvalidArgumentException('Initial balance cannot be negative');
        }
        $this->balance = $initialBalance;
    }

    public function deposit(float $amount): void
    {
        if ($amount <= 0) {
            throw new \InvalidArgumentException('Deposit amount must be positive');
        }
        $this->balance += $amount;
        $this->transactions[] = ['type' => 'deposit', 'amount' => $amount];
    }

    public function withdraw(float $amount): void
    {
        if ($amount > $this->balance) {
            throw new \DomainException('Insufficient funds');
        }
        $this->balance -= $amount;
        $this->transactions[] = ['type' => 'withdrawal', 'amount' => $amount];
    }

    public function getBalance(): float
    {
        return $this->balance;
    }

    public function getTransactions(): array
    {
        return $this->transactions;
    }
}
抽象

面向接口编程,而非面向实现编程。通过接口和抽象类定义契约。

<?php

declare(strict_types=1);

// Define the contract
interface PaymentGatewayInterface
{
    public function charge(float $amount, string $currency): PaymentResult;
    public function refund(string $transactionId): bool;
}

// One implementation
class StripeGateway implements PaymentGatewayInterface
{
    public function charge(float $amount, string $currency): PaymentResult
    {
        // Stripe-specific implementation
    }

    public function refund(string $transactionId): bool
    {
        // Stripe-specific implementation
    }
}

// Another implementation — same contract
class PaystackGateway implements PaymentGatewayInterface
{
    public function charge(float $amount, string $currency): PaymentResult
    {
        // Paystack-specific implementation
    }

    public function refund(string $transactionId): bool
    {
        // Paystack-specific implementation
    }
}

// Consumer depends on the interface, not the implementation
class OrderService
{
    private PaymentGatewayInterface $gateway;

    public function __construct(PaymentGatewayInterface $gateway)
    {
        $this->gateway = $gateway;
    }

    public function checkout(Order $order): void
    {
        $result = $this->gateway->charge($order->getTotal(), $order->getCurrency());
        // ...
    }
}
组合优于继承

优先注入协作者,而不是扩展类。继承会造成紧密耦合。

<?php

declare(strict_types=1);

// BAD — deep inheritance chain
class Animal {}
class Dog extends Animal {}
class ServiceDog extends Dog {} // fragile, tightly coupled

// GOOD — compose behaviours
interface CanBark
{
    public function bark(): string;
}

interface CanFetch
{
    public function fetch(): string;
}

class BarkBehaviour implements CanBark
{
    public function bark(): string
    {
        return 'Woof!';
    }
}

class FetchBehaviour implements CanFetch
{
    public function fetch(): string
    {
        return 'Fetching...';
    }
}

class Dog
{
    private CanBark $barkBehaviour;
    private CanFetch $fetchBehaviour;

    public function __construct(CanBark $barkBehaviour, CanFetch $fetchBehaviour)
    {
        $this->barkBehaviour = $barkBehaviour;
        $this->fetchBehaviour = $fetchBehaviour;
    }

    public function bark(): string
    {
        return $this->barkBehaviour->bark();
    }

    public function fetch(): string
    {
        return $this->fetchBehaviour->fetch();
    }
}
多态

不同的类,相同的接口——调用方无需知道自己使用的是哪种实现。

<?php

declare(strict_types=1);

interface NotificationInterface
{
    public function send(string $recipient, string $message): void;
}

class EmailNotification implements NotificationInterface
{
    public function send(string $recipient, string $message): void
    {
        // send via email
    }
}

class SmsNotification implements NotificationInterface
{
    public function send(string $recipient, string $message): void
    {
        // send via SMS
    }
}

class SlackNotification implements NotificationInterface
{
    public function send(string $recipient, string $message): void
    {
        // send via Slack
    }
}

class NotificationService
{
    /** @var NotificationInterface[] */
    private array $channels;

    public function __construct(NotificationInterface ...$channels)
    {
        $this->channels = $channels;
    }

    public function notify(string $recipient, string $message): void
    {
        foreach ($this->channels as $channel) {
            $channel->send($recipient, $message); // polymorphic — doesn't care which channel
        }
    }
}

SOLID 原则

S — 单一职责

一个类应该只有一个改变的理由。

// BAD — does too many things
class User
{
    public function save(): void { /* DB logic */ }
    public function sendWelcomeEmail(): void { /* Email logic */ }
    public function validateEmail(): bool { /* Validation logic */ }
}

// GOOD — each class has one job
class User { /* Only user state */ }
class UserRepository { /* Only DB persistence */ }
class UserMailer { /* Only email */ }
class EmailValidator { /* Only validation */ }
O — 开闭原则

对扩展开放,对修改关闭。

<?php

declare(strict_types=1);

interface DiscountInterface
{
    public function apply(float $price): float;
}

class PercentageDiscount implements DiscountInterface
{
    private float $percentage;

    public function __construct(float $percentage)
    {
        $this->percentage = $percentage;
    }

    public function apply(float $price): float
    {
        return $price * (1 - $this->percentage / 100);
    }
}

class FlatDiscount implements DiscountInterface
{
    private float $amount;

    public function __construct(float $amount)
    {
        $this->amount = $amount;
    }

    public function apply(float $price): float
    {
        return max(0, $price - $this->amount);
    }
}

// Adding a new discount type doesn't touch existing code
class BuyOneGetOneDiscount implements DiscountInterface
{
    public function apply(float $price): float
    {
        return $price / 2;
    }
}
L — 里氏替换原则

子类型必须能够替换其基类型,而不影响正确性。

<?php

declare(strict_types=1);

abstract class Shape
{
    abstract public function area(): float;
}

class Rectangle extends Shape
{
    private float $width;
    private float $height;

    public function __construct(
        float $width,
        float $height
    ) {
        $this->width = $width;
        $this->height = $height;
    }

    public function area(): float
    {
        return $this->width * $this->height;
    }
}

class Circle extends Shape
{
    private float $radius;

    public function __construct(float $radius)
    {
        $this->radius = $radius;
    }

    public function area(): float
    {
        return M_PI * $this->radius ** 2;
    }
}

// Works with any Shape subtype — LSP satisfied
function printArea(Shape $shape): void
{
    echo $shape->area();
}
I — 接口隔离原则

不应强迫任何类实现自己不会使用的方法。拆分臃肿的接口。

// BAD — fat interface
interface WorkerInterface
{
    public function work(): void;
    public function eat(): void;
    public function sleep(): void;
}

// GOOD — segregated interfaces
interface WorkableInterface
{
    public function work(): void;
}

interface EatableInterface
{
    public function eat(): void;
}

class HumanWorker implements WorkableInterface, EatableInterface
{
    public function work(): void { /* ... */ }
    public function eat(): void { /* ... */ }
}

class RobotWorker implements WorkableInterface
{
    public function work(): void { /* ... */ }
    // robots don't eat — not forced to implement it
}
D — 依赖倒置原则

高层模块不应依赖低层模块。两者都应依赖抽象。

<?php

declare(strict_types=1);

// Abstraction
interface LoggerInterface
{
    public function log(string $message): void;
}

// Low-level module
class FileLogger implements LoggerInterface
{
    public function log(string $message): void
    {
        file_put_contents('/var/log/app.log', $message . PHP_EOL, FILE_APPEND);
    }
}

// High-level module depends on abstraction, not FileLogger directly
class OrderProcessor
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function process(Order $order): void
    {
        $this->logger->log("Processing order #{$order->getId()}");
        // ...
    }
}

设计模式

仓储模式

抽象数据访问。业务逻辑绝不直接访问数据库。

<?php

declare(strict_types=1);

interface UserRepositoryInterface
{
    public function findById(int $id): ?User;
    public function findByEmail(string $email): ?User;
    /** @return User[] */
    public function findAll(): array;
    public function save(User $user): void;
    public function delete(int $id): void;
}

class PdoUserRepository implements UserRepositoryInterface
{
    private \PDO $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findById(int $id): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $row ? User::fromArray($row) : null;
    }

    public function findByEmail(string $email): ?User
    {
        $stmt = $this->db->prepare('SELECT * FROM users WHERE email = :email LIMIT 1');
        $stmt->execute(['email' => $email]);
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);

        return $row ? User::fromArray($row) : null;
    }

    public function findAll(): array
    {
        $stmt = $this->db->query('SELECT * FROM users');
        return array_map(fn($row) => User::fromArray($row), $stmt->fetchAll(\PDO::FETCH_ASSOC));
    }

    public function save(User $user): void
    {
        if ($user->getId() === null) {
            $stmt = $this->db->prepare(
                'INSERT INTO users (email, password_hash, created_at) VALUES (:email, :password_hash, :created_at)'
            );
        } else {
            $stmt = $this->db->prepare(
                'UPDATE users SET email = :email, password_hash = :password_hash WHERE id = :id'
            );
        }
        $stmt->execute($user->toArray());
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM users WHERE id = :id');
        $stmt->execute(['id' => $id]);
    }
}
服务层

业务逻辑位于此处。负责协调仓储、验证数据和分发事件。

<?php

declare(strict_types=1);

class UserService
{
    private UserRepositoryInterface $users;
    private PasswordHasherInterface $hasher;
    private NotificationInterface $notifier;

    public function __construct(
        UserRepositoryInterface $users,
        PasswordHasherInterface $hasher,
        NotificationInterface $notifier
    ) {
        $this->users = $users;
        $this->hasher = $hasher;
        $this->notifier = $notifier;
    }

    public function register(string $email, string $password): User
    {
        if ($this->users->findByEmail($email)) {
            throw new DuplicateEmailException("Email already registered: {$email}");
        }

        $user = new User(
            new Email($email),
            $this->hasher->hash($password)
        );

        $this->users->save($user);
        $this->notifier->send($email, 'Welcome!');

        return $user;
    }

    public function changePassword(int $userId, string $currentPassword, string $newPassword): void
    {
        $user = $this->users->findById($userId);

        if (!$user) {
            throw new UserNotFoundException($userId);
        }

        if (!$this->hasher->verify($currentPassword, $user->getPasswordHash())) {
            throw new InvalidPasswordException();
        }

        $user->setPasswordHash($this->hasher->hash($newPassword));
        $this->users->save($user);
    }
}
值对象

不可变且能自行验证、用于表示领域概念的对象。

<?php

declare(strict_types=1);

final class Email
{
    private string $value;

    public function __construct(string $value)
    {
        $value = strtolower(trim($value));

        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException("Invalid email address: {$value}");
        }

        $this->value = $value;
    }

    public function getValue(): string
    {
        return $this->value;
    }

    public function equals(self $other): bool
    {
        return $this->value === $other->value;
    }

    public function __toString(): string
    {
        return $this->value;
    }
}

final class Money
{
    private int $amount; // store in smallest unit (cents)
    private string $currency;

    public function __construct(int $amount, string $currency)
    {
        if ($amount < 0) {
            throw new \InvalidArgumentException('Amount cannot be negative');
        }
        $this->amount = $amount;
        $this->currency = strtoupper($currency);
    }

    public function add(self $other): self
    {
        if ($this->currency !== $other->currency) {
            throw new \DomainException('Cannot add different currencies');
        }
        return new self($this->amount + $other->amount, $this->currency);
    }

    public function getAmount(): int
    {
        return $this->amount;
    }

    public function getCurrency(): string
    {
        return $this->currency;
    }
}
工厂模式

集中处理复杂的对象创建过程。

<?php

declare(strict_types=1);

interface NotificationInterface
{
    public function send(string $recipient, string $message): void;
}

class NotificationFactory
{
    public function create(string $channel): NotificationInterface
    {
        switch ($channel) {
            case 'email':
                return new EmailNotification();
            case 'sms':
                return new SmsNotification();
            case 'slack':
                return new SlackNotification();
            default:
                throw new \InvalidArgumentException("Unknown channel: {$channel}");
        }
    }
}
策略模式

在运行时切换算法,而无需更改使用方。

<?php

declare(strict_types=1);

interface SortStrategyInterface
{
    /** @param int[] $data */
    public function sort(array $data): array;
}

class BubbleSortStrategy implements SortStrategyInterface
{
    public function sort(array $data): array
    {
        // bubble sort implementation
        return $data;
    }
}

class QuickSortStrategy implements SortStrategyInterface
{
    public function sort(array $data): array
    {
        sort($data);
        return $data;
    }
}

class DataSorter
{
    private SortStrategyInterface $strategy;

    public function __construct(SortStrategyInterface $strategy)
    {
        $this->strategy = $strategy;
    }

    public function setStrategy(SortStrategyInterface $strategy): void
    {
        $this->strategy = $strategy;
    }

    public function sort(array $data): array
    {
        return $this->strategy->sort($data);
    }
}
观察者模式

解耦事件生产者与事件使用者。

<?php

declare(strict_types=1);

interface ObserverInterface
{
    public function update(string $event, $payload = null): void;
}

interface ObservableInterface
{
    public function subscribe(string $event, ObserverInterface $observer): void;
    public function notify(string $event, $payload = null): void;
}

class EventEmitter implements ObservableInterface
{
    /** @var array<string, ObserverInterface[]> */
    private array $listeners = [];

    public function subscribe(string $event, ObserverInterface $observer): void
    {
        $this->listeners[$event][] = $observer;
    }

    public function notify(string $event, $payload = null): void
    {
        foreach ($this->listeners[$event] ?? [] as $observer) {
            $observer->update($event, $payload);
        }
    }
}

class UserRegisteredObserver implements ObserverInterface
{
    private NotificationInterface $notifier;

    public function __construct(NotificationInterface $notifier)
    {
        $this->notifier = $notifier;
    }

    public function update(string $event, $payload = null): void
    {
        if ($event === 'user.registered' && $payload instanceof User) {
            $this->notifier->send($payload->getEmail(), 'Welcome!');
        }
    }
}
装饰器模式

无需继承即可扩展对象的行为。

<?php

declare(strict_types=1);

interface LoggerInterface
{
    public function log(string $message): void;
}

class FileLogger implements LoggerInterface
{
    public function log(string $message): void
    {
        file_put_contents('/var/log/app.log', $message . PHP_EOL, FILE_APPEND);
    }
}

class TimestampLogger implements LoggerInterface
{
    private LoggerInterface $inner;

    public function __construct(LoggerInterface $inner)
    {
        $this->inner = $inner;
    }

    public function log(string $message): void
    {
        $this->inner->log('[' . date('Y-m-d H:i:s') . '] ' . $message);
    }
}

class PrefixLogger implements LoggerInterface
{
    private LoggerInterface $inner;
    private string $prefix;

    public function __construct(LoggerInterface $inner, string $prefix)
    {
        $this->inner = $inner;
        $this->prefix = $prefix;
    }

    public function log(string $message): void
    {
        $this->inner->log("[{$this->prefix}] {$message}");
    }
}

// Usage — chain decorators
$logger = new TimestampLogger(new PrefixLogger(new FileLogger(), 'APP'));
$logger->log('User registered'); // [2026-02-21 10:00:00] [APP] User registered
依赖注入容器
<?php

declare(strict_types=1);

class Container
{
    private array $bindings = [];
    private array $instances = [];

    public function bind(string $abstract, callable $factory): void
    {
        $this->bindings[$abstract] = $factory;
    }

    public function singleton(string $abstract, callable $factory): void
    {
        $this->bindings[$abstract] = function () use ($abstract, $factory) {
            if (!isset($this->instances[$abstract])) {
                $this->instances[$abstract] = $factory($this);
            }
            return $this->instances[$abstract];
        };
    }

    public function make(string $abstract): object
    {
        if (isset($this->bindings[$abstract])) {
            return ($this->bindings[$abstract])($this);
        }
        throw new \RuntimeException("No binding registered for: {$abstract}");
    }
}

// Bootstrap
$container = new Container();

$container->singleton(\PDO::class, fn() => new \PDO(
    'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8mb4',
    getenv('DB_USER'),
    getenv('DB_PASS'),
    [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC]
));

$container->bind(UserRepositoryInterface::class, fn($c) => new PdoUserRepository($c->make(\PDO::class)));
$container->bind(UserService::class, fn($c) => new UserService(
    $c->make(UserRepositoryInterface::class),
    new BcryptPasswordHasher(),
    new EmailNotification()
));

安全(不可妥协)

SQL — 始终使用预处理语句
// ❌ NEVER
$result = $db->query("SELECT * FROM users WHERE email = '{$email}'");

// ✅ ALWAYS
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
XSS 防护
// Escape all output
echo htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// JSON output
header('Content-Type: application/json');
echo json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
CSRF 防护
// Generate
$_SESSION['csrf_token'] ??= bin2hex(random_bytes(32));

// Validate
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    throw new CsrfException('Invalid CSRF token');
}
密码
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
if (!password_verify($input, $storedHash)) {
    throw new AuthenticationException();
}
文件上传
function validateUpload(array $file, array $allowedMimes): void
{
    $finfo = new \finfo(FILEINFO_MIME_TYPE);
    $mime = $finfo->file($file['tmp_name']);

    if (!in_array($mime, $allowedMimes, true)) {
        throw new \InvalidArgumentException("File type not allowed: {$mime}");
    }

    if ($file['size'] > 5 * 1024 * 1024) {
        throw new \RuntimeException('File exceeds 5MB limit');
    }
}

错误处理

<?php

declare(strict_types=1);

// Exception hierarchy
class AppException extends \RuntimeException {}
class NotFoundException extends AppException {}
class ValidationException extends AppException
{
    private array $errors;

    public function __construct(array $errors)
    {
        parent::__construct('Validation failed');
        $this->errors = $errors;
    }

    public function getErrors(): array
    {
        return $this->errors;
    }
}
class AuthenticationException extends AppException {}
class DuplicateEmailException extends AppException {}

// Global handler
set_exception_handler(function (\Throwable $e) {
    error_log(sprintf(
        '[%s] %s in %s:%d',
        get_class($e),
        $e->getMessage(),
        $e->getFile(),
        $e->getLine()
    ));

    http_response_code($e instanceof NotFoundException ? 404 : 500);

    if (getenv('APP_ENV') === 'production') {
        echo json_encode(['error' => 'Something went wrong']);
    } else {
        echo json_encode(['error' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
    }
});

数据库(PDO 最佳实践)

<?php

declare(strict_types=1);

class Database
{
    private static ?\PDO $instance = null;

    public static function getInstance(): \PDO
    {
        if (self::$instance === null) {
            self::$instance = new \PDO(
                sprintf(
                    'mysql:host=%s;dbname=%s;charset=utf8mb4',
                    getenv('DB_HOST'),
                    getenv('DB_NAME')
                ),
                getenv('DB_USER'),
                getenv('DB_PASS'),
                [
                    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                    \PDO::ATTR_EMULATE_PREPARES   => false,
                ]
            );
        }
        return self::$instance;
    }
}

// Transactions
function withTransaction(\PDO $pdo, callable $callback)
{
    $pdo->beginTransaction();
    try {
        $result = $callback($pdo);
        $pdo->commit();
        return $result;
    } catch (\Throwable $e) {
        $pdo->rollBack();
        throw $e;
    }
}

性能

  • 在 php.ini 中启用 OPcache——opcache.enable=1
  • 使用 PDO::FETCH_ASSOC,不要使用 PDO::FETCH_OBJ(速度更快)
  • 避免 N+1 查询——使用 JOIN 或批量获取
  • 使用 APCu 或基于文件的缓存来缓存开销较大的操作
  • 在表达意图更清晰时使用 array_map、array_filter、array_reduce
  • 避免加载不需要的文件——利用 PSR-4 自动加载
  • 尽可能使用 isset(),而不是 array_key_exists()(速度更快)
  • 优先使用 foreach,而不是 while + each()(在 7.2 中已弃用)
  • 在循环条件之外调用 count(),避免重复调用
// BAD — count() called every iteration
for ($i = 0; $i < count($items); $i++) { }

// GOOD — count() called once
$total = count($items);
for ($i = 0; $i < $total; $i++) { }

输入验证

<?php

declare(strict_types=1);

class Validator
{
    private array $errors = [];

    public function required(string $field, $value): self
    {
        if (empty($value) && $value !== '0') {
            $this->errors[$field][] = "{$field} is required";
        }
        return $this;
    }

    public function email(string $field, string $value): self
    {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field][] = "{$field} must be a valid email";
        }
        return $this;
    }

    public function minLength(string $field, string $value, int $min): self
    {
        if (mb_strlen($value) < $min) {
            $this->errors[$field][] = "{$field} must be at least {$min} characters";
        }
        return $this;
    }

    public function maxLength(string $field, string $value, int $max): self
    {
        if (mb_strlen($value) > $max) {
            $this->errors[$field][] = "{$field} must not exceed {$max} characters";
        }
        return $this;
    }

    public function integer(string $field, $value): self
    {
        if (!filter_var($value, FILTER_VALIDATE_INT)) {
            $this->errors[$field][] = "{$field} must be an integer";
        }
        return $this;
    }

    public function passes(): bool
    {
        return empty($this->errors);
    }

    public function getErrors(): array
    {
        return $this->errors;
    }

    public function validate(): void
    {
        if (!$this->passes()) {
            throw new ValidationException($this->errors);
        }
    }
}

测试(PHPUnit)

<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;

class UserServiceTest extends TestCase
{
    private UserService $service;
    private UserRepositoryInterface $repository;
    private PasswordHasherInterface $hasher;

    protected function setUp(): void
    {
        $this->repository = $this->createMock(UserRepositoryInterface::class);
        $this->hasher     = $this->createMock(PasswordHasherInterface::class);
        $this->service    = new UserService(
            $this->repository,
            $this->hasher,
            $this->createMock(NotificationInterface::class)
        );
    }

    public function testRegisterCreatesUserSuccessfully(): void
    {
        $this->repository->method('findByEmail')->willReturn(null);
        $this->hasher->method('hash')->willReturn('hashed_password');
        $this->repository->expects($this->once())->method('save');

        $user = $this->service->register('[email protected]', 'password123');

        $this->assertInstanceOf(User::class, $user);
    }

    public function testRegisterThrowsOnDuplicateEmail(): void
    {
        $this->repository
            ->method('findByEmail')
            ->willReturn(new User(new Email('[email protected]'), 'hash'));

        $this->expectException(DuplicateEmailException::class);

        $this->service->register('[email protected]', 'password123');
    }
}

静态分析

由于 PHP 7.4 不支持原生联合类型,请使用静态分析工具在运行前捕获类型错误。

PHPStan
composer require --dev phpstan/phpstan

phpstan.neon

parameters:
    level: 8
    paths:
        - src
        - tests
    excludePaths:
        - tests/bootstrap.php

运行:

vendor/bin/phpstan analyse
Psalm
composer require --dev vimeo/psalm

psalm.xml

<?xml version="1.0"?>
<psalm
    errorLevel="3"
    resolveFromConfigFile="true"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://getpsalm.org/schema/config"
    xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
>
    <projectFiles>
        <directory name="src" />
        <ignoreFiles>
            <directory name="vendor" />
        </ignoreFiles>
    </projectFiles>
</psalm>

运行:

vendor/bin/psalm
高级类型的 PHPDoc

使用 PHPDoc 记录 PHP 7.4 无法原生表达的类型:

<?php

declare(strict_types=1);

class UserRepository
{
    /**
     * @return array<int, User>
     */
    public function findAll(): array
    {
        // Returns an array with integer keys and User values
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(User $user): array
    {
        // Returns associative array with string keys
    }

    /**
     * @param array<string, string> $filters
     * @return User[]
     */
    public function search(array $filters): array
    {
        // Accepts array of string filters, returns list of Users
    }

    /**
     * @param int|string $id
     * @return User|null
     */
    public function find($id): ?User
    {
        // Union types via PHPDoc (not available natively in 7.4)
    }

    /**
     * @return array{id: int, email: string, created_at: string}
     */
    public function getUserData(int $id): array
    {
        // Shaped array with specific keys
    }

    /**
     * @return iterable<User>
     */
    public function getGenerator(): iterable
    {
        // Generic iterable type
    }

    /**
     * @template T
     * @param class-string<T> $className
     * @return T
     */
    public function make(string $className): object
    {
        // Generic template types
    }
}

关键 PHPDoc 注解:

  • @param Type $name — 参数类型
  • @return Type — 返回类型
  • @var Type — 属性或变量类型
  • @throws ExceptionClass — 记录抛出的异常
  • array<KeyType, ValueType> — 类型化数组
  • array{key: Type, ...} — 形状化数组
  • Type1|Type2 — 联合类型
  • Type[] — array<int, Type> 的简写
  • @template T — 泛型
  • class-string<T> — 类名字符串

项目结构(PSR-4)

src/
├── Controllers/       # HTTP layer only — no business logic
├── Services/          # Business logic
├── Repositories/      # Data access
├── Models/            # Domain entities
├── ValueObjects/      # Immutable domain concepts
├── Exceptions/        # Custom exception hierarchy
├── Interfaces/        # All contracts/interfaces
├── Factories/         # Object creation
└── Support/           # Helpers, utilities

tests/
├── Unit/
└── Integration/

public/
└── index.php          # Entry point

config/
└── container.php      # DI bindings

.env
composer.json
composer.json 示例
{
    "name": "vendor/project-name",
    "description": "PHP 7.4 application",
    "type": "project",
    "require": {
        "php": "^7.4"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.5",
        "phpstan/phpstan": "^1.10",
        "squizlabs/php_codesniffer": "^3.7"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "scripts": {
        "test": "phpunit",
        "analyse": "phpstan analyse",
        "cs": "phpcs --standard=PSR12 src tests"
    }
}

使用此配置:

  • App\Controllers\UserController → src/Controllers/UserController.php
  • App\Services\UserService → src/Services/UserService.php
  • App\Tests\Unit\UserServiceTest → tests/Unit/UserServiceTest.php

添加新类后运行 composer dump-autoload。


必须做 / 禁止做

✅ 必须做到
  • 在每个文件中使用 declare(strict_types=1)
  • 为所有属性、参数和返回值添加类型提示
  • 所有数据库查询都使用预处理语句
  • 依赖接口,而非具体类
  • 使用 DI 注入基础设施依赖;值对象和简单的内部构造可以使用 new
  • 保持类小巧且职责明确(SRP)
  • 使用前验证所有用户输入
  • 使用 password_hash() / password_verify()
  • 为数组和复杂类型编写 PHPDoc
  • 通过接口使用模拟对象进行测试
❌ 必须避免
  • 在 PHP 7.4 代码库中使用 PHP 8.x 特性
  • 通过字符串拼接编写原始 SQL
  • 将机密信息存储在代码中——使用 .env
  • 使用 global 关键字
  • 使用 extract()、eval()、$$variable
  • 使用 @抑制错误
  • 在控制器中编写业务逻辑
  • 创建包揽一切的上帝类
  • 应该组合时却使用继承
  • 跳过错误处理——绝不静默吞掉异常

评论

支持 Markdown