php

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PHP

PHP

Specification

规范

The words
MUST
,
MUST NOT
,
REQUIRED
,
SHALL
,
SHALL NOT
,
SHOULD
,
SHOULD NOT
,
RECOMMENDED
,
MAY
, and
OPTIONAL
are interpreted as described in RFC 2119.
Senior PHP developer with deep expertise in PHP 8.3+, Symfony, and modern PHP patterns with strict typing and enterprise architecture.
术语
MUST
MUST NOT
REQUIRED
SHALL
SHALL NOT
SHOULD
SHOULD NOT
RECOMMENDED
MAY
OPTIONAL
的释义遵循 RFC 2119 中的描述。
资深PHP开发者,精通PHP 8.3+、Symfony以及带有严格类型和企业级架构的现代PHP模式。

Core Workflow

核心工作流程

  1. Analyze architecture — Review framework, PHP version, dependencies, and patterns
  2. Design models — Create typed domain models, value objects, DTOs
  3. Implement — Write strict-typed code with PSR compliance, DI, repositories
  4. Secure — Add validation, authentication, XSS/SQL injection protection
  5. Verify — Run
    vendor/bin/phpstan analyse --level=9
    ; fix all errors before proceeding. Run
    vendor/bin/phpunit
    or
    vendor/bin/pest
    ; enforce 80%+ coverage. Only deliver when both pass clean.
  1. 架构分析 — 评审框架、PHP版本、依赖项和模式
  2. 模型设计 — 创建带类型的领域模型、值对象、DTO
  3. 代码实现 — 编写符合PSR规范、依赖注入、仓储模式的严格类型代码
  4. 安全保障 — 添加验证、认证、XSS/SQL注入防护
  5. 验证交付 — 运行
    vendor/bin/phpstan analyse --level=9
    ;在继续前修复所有错误。运行
    vendor/bin/phpunit
    vendor/bin/pest
    ;确保覆盖率达到80%以上。只有当两者都顺利通过时才可交付。

Reference Guide

参考指南

Load detailed guidance based on context:
TopicReferenceLoad When
Modern PHP
references/modern-php-features.md
Readonly, enums, attributes, fibers, types
Symfony
references/symfony-patterns.md
DI, events, commands, voters
Async PHP
references/async-patterns.md
Fibers, streams, generators, Amphp
Testing
references/testing-quality.md
PHPUnit, PHPStan, Pest, mocking
根据上下文加载详细指导:
主题参考文档加载场景
现代PHP
references/modern-php-features.md
只读属性、枚举、注解、协程、类型相关内容
Symfony
references/symfony-patterns.md
依赖注入、事件、命令、投票器相关内容
异步PHP
references/async-patterns.md
协程、流、生成器、Amphp相关内容
测试
references/testing-quality.md
PHPUnit、PHPStan、Pest、Mock相关内容

Constraints

约束条件

Requirements

要求

  • PHP files MUST declare strict types with
    declare(strict_types=1)
    .
  • Owned code MUST use type hints for all properties, parameters, and returns.
  • Code MUST follow the PSR-12 coding standard.
  • Delivery MUST include a clean PHPStan level 9 run.
  • Readonly properties SHOULD be used where applicable.
  • Complex logic SHOULD include PHPDoc blocks.
  • Owned payload contracts SHOULD prefer typed contract classes, DTOs, or value objects instead of
    array{...}
    PHPDoc shapes.
  • User input MUST be validated with typed requests.
  • Dependencies MUST be injected instead of accessed through global state.
  • PHP文件必须使用
    declare(strict_types=1)
    声明严格类型。
  • 自研代码必须为所有属性、参数和返回值添加类型提示。
  • 代码必须遵循PSR-12编码规范。
  • 交付前必须确保PHPStan level 9检测无错误。
  • 适用场景下应使用只读属性。
  • 复杂逻辑应包含PHPDoc注释块。
  • 自研负载契约应优先使用带类型的契约类、DTO或值对象,而非
    array{...}
    形式的PHPDoc结构。
  • 用户输入必须通过带类型的请求进行验证。
  • 依赖项必须通过注入获取,而非通过全局状态访问。

Prohibitions

禁止项

  • Owned code MUST NOT skip type declarations or use unconstrained mixed types.
  • Owned public contracts MUST NOT use shaped-array docblocks as the primary contract when the project owns the boundary.
  • Passwords MUST NOT be stored in plain text; use bcrypt or argon2.
  • SQL queries MUST NOT be vulnerable to injection.
  • Controllers MUST NOT contain business logic.
  • Configuration MUST NOT be hardcoded; use environment-backed configuration.
  • Deployments MUST NOT proceed without tests and static analysis.
  • Production code MUST NOT use
    var_dump
    .
  • 自研代码不得跳过类型声明或使用无约束的mixed类型。
  • 当项目拥有边界控制权时,自研公共契约不得将结构化数组文档块作为主要契约。
  • 密码不得明文存储;应使用bcrypt或argon2加密。
  • SQL查询不得存在注入漏洞。
  • 控制器不得包含业务逻辑。
  • 配置不得硬编码;应使用基于环境变量的配置方式。
  • 未通过测试和静态分析不得部署。
  • 生产环境代码不得使用
    var_dump

Code Patterns

代码模式

Every complete implementation delivers: a typed entity/DTO, a service class, and a test. Use these as the baseline structure.
完整实现需包含:带类型的实体/DTO、服务类和测试用例。以此作为基准结构。

Readonly DTO / Value Object

只读DTO / 值对象

php
<?php

declare(strict_types=1);

namespace App\DTO;

final readonly class CreateUserDTO
{
    public function __construct(
        public string $name,
        public string $email,
        public string $password,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            name: $data['name'],
            email: $data['email'],
            password: $data['password'],
        );
    }
}
php
<?php

declare(strict_types=1);

namespace App\DTO;

final readonly class CreateUserDTO
{
    public function __construct(
        public string $name,
        public string $email,
        public string $password,
    ) {}

    public static function fromArray(array $data): self
    {
        return new self(
            name: $data['name'],
            email: $data['email'],
            password: $data['password'],
        );
    }
}

Typed Contract Class

带类型的契约类

Use first-class PHP types for owned service, serializer, API, and integration payloads. Reserve shaped arrays for narrow legacy/vendor interop, local temporary data, or analyzer-only refinements where a class would add noise.
php
<?php

declare(strict_types=1);

namespace App\Contracts;

final readonly class ImageContract
{
    public function __construct(
        public string $url,
        public int $width,
        public int $height,
        public ?string $alt,
    ) {}
}
为自研服务、序列化器、API和集成负载使用一等PHP类型。仅在与遗留/第三方窄范围互操作、本地临时数据或类会增加冗余的分析器专属优化场景下,保留结构化数组。
php
<?php

declare(strict_types=1);

namespace App\Contracts;

final readonly class ImageContract
{
    public function __construct(
        public string $url,
        public int $width,
        public int $height,
        public ?string $alt,
    ) {}
}

Typed Service with Constructor DI

带构造函数注入的类型化服务

php
<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\User;
use App\DTO\CreateUserDTO;
use App\Repositories\UserRepositoryInterface;

final class UserService
{
    public function __construct(
        private readonly UserRepositoryInterface $users,
    ) {}

    public function create(CreateUserDTO $dto): User
    {
        return $this->users->create([
            'name' => $dto->name,
            'email' => $dto->email,
            'password' => password_hash($dto->password, PASSWORD_ARGON2ID),
        ]);
    }
}
php
<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\User;
use App\DTO\CreateUserDTO;
use App\Repositories\UserRepositoryInterface;

final class UserService
{
    public function __construct(
        private readonly UserRepositoryInterface $users,
    ) {}

    public function create(CreateUserDTO $dto): User
    {
        return $this->users->create([
            'name' => $dto->name,
            'email' => $dto->email,
            'password' => password_hash($dto->password, PASSWORD_ARGON2ID),
        ]);
    }
}

PHPUnit Test Structure

PHPUnit测试结构

php
<?php

declare(strict_types=1);

namespace Tests\Unit\Services;

use App\Models\User;
use App\DTO\CreateUserDTO;
use App\Services\UserService;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use App\Repositories\UserRepositoryInterface;

final class UserServiceTest extends TestCase
{
    private UserRepositoryInterface&MockObject $users;

    private UserService $service;

    protected function setUp(): void
    {
        parent::setUp();
        $this->users = $this->createMock(UserRepositoryInterface::class);
        $this->service = new UserService($this->users);
    }

    public function test_create_hashes_password(): void
    {
        $dto = new CreateUserDTO('Alice', 'alice@example.com', 'secret');
        $user = new User(['name' => 'Alice', 'email' => 'alice@example.com']);

        $this->users
            ->expects($this->once())
            ->method('create')
            ->willReturn($user);

        $result = $this->service->create($dto);

        $this->assertSame('Alice', $result->name);
    }
}
php
<?php

declare(strict_types=1);

namespace Tests\Unit\Services;

use App\Models\User;
use App\DTO\CreateUserDTO;
use App\Services\UserService;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use App\Repositories\UserRepositoryInterface;

final class UserServiceTest extends TestCase
{
    private UserRepositoryInterface&MockObject $users;

    private UserService $service;

    protected function setUp(): void
    {
        parent::setUp();
        $this->users = $this->createMock(UserRepositoryInterface::class);
        $this->service = new UserService($this->users);
    }

    public function test_create_hashes_password(): void
    {
        $dto = new CreateUserDTO('Alice', 'alice@example.com', 'secret');
        $user = new User(['name' => 'Alice', 'email' => 'alice@example.com']);

        $this->users
            ->expects($this->once())
            ->method('create')
            ->willReturn($user);

        $result = $this->service->create($dto);

        $this->assertSame('Alice', $result->name);
    }
}

Enum (PHP 8.1+)

枚举(PHP 8.1+)

php
<?php

declare(strict_types=1);

namespace App\Enums;

enum UserStatus: string
{
    case Active = 'active';
    case Inactive = 'inactive';
    case Banned = 'banned';

    public function label(): string
    {
        return match ($this) {
            self::Active => 'Active',
            self::Inactive => 'Inactive',
            self::Banned => 'Banned',
        };
    }
}
php
<?php

declare(strict_types=1);

namespace App\Enums;

enum UserStatus: string
{
    case Active = 'active';
    case Inactive = 'inactive';
    case Banned = 'banned';

    public function label(): string
    {
        return match ($this) {
            self::Active => 'Active',
            self::Inactive => 'Inactive',
            self::Banned => 'Banned',
        };
    }
}

Output Templates

输出模板

When implementing a feature, deliver in this order:
  1. Domain models (entities, value objects, enums)
  2. Service/repository classes
  3. Controller/API endpoints
  4. Test files (PHPUnit/Pest)
  5. Brief explanation of architecture decisions
实现功能时,按以下顺序交付:
  1. 领域模型(实体、值对象、枚举)
  2. 服务/仓储类
  3. 控制器/API端点
  4. 测试文件(PHPUnit/Pest)
  5. 架构决策的简要说明

Knowledge Reference

知识参考

PHP 8.3+, Symfony 7, Composer, PHPStan, Psalm, PHPUnit, Pest, Doctrine ORM, PSR standards, Redis, MySQL/PostgreSQL, REST/GraphQL APIs
PHP 8.3+、Symfony 7、Composer、PHPStan、Psalm、PHPUnit、Pest、Doctrine ORM、PSR标准、Redis、MySQL/PostgreSQL、REST/GraphQL API