moai-lang-php

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quick Reference (30 seconds)

快速参考(30秒)

PHP 8.3+ Development Specialist - Laravel 11, Symfony 7, Eloquent, Doctrine, and modern PHP patterns.
Auto-Triggers: PHP files with .php extension, composer.json, artisan command, symfony.yaml, Laravel or Symfony discussions
Core Capabilities:
  • PHP 8.3 Features: readonly classes, typed properties, attributes, enums, named arguments
  • Laravel 11: Controllers, Models, Migrations, Form Requests, API Resources, Eloquent
  • Symfony 7: Attribute-based routing, Doctrine ORM, Services, Dependency Injection
  • ORMs: Eloquent for Laravel, Doctrine for Symfony
  • Testing: PHPUnit, Pest, feature and unit testing patterns
  • Package Management: Composer with autoloading
  • Coding Standards: PSR-12, Laravel Pint, PHP CS Fixer
  • Docker: PHP-FPM, nginx, multi-stage builds
PHP 8.3+开发专家 - 精通Laravel 11、Symfony 7、Eloquent、Doctrine以及现代PHP设计模式。
自动触发场景:.php后缀的PHP文件、composer.json、artisan命令、symfony.yaml、Laravel或Symfony相关讨论
核心能力:
  • PHP 8.3特性:只读类、类型化属性、注解、枚举、命名参数
  • Laravel 11:控制器、模型、迁移、表单请求、API资源、Eloquent
  • Symfony 7:基于注解的路由、Doctrine ORM、服务、依赖注入
  • ORM:Laravel的Eloquent、Symfony的Doctrine
  • 测试:PHPUnit、Pest、功能测试与单元测试模式
  • 包管理:带自动加载的Composer
  • 编码规范:PSR-12、Laravel Pint、PHP CS Fixer
  • Docker:PHP-FPM、nginx、多阶段构建

Quick Patterns

快速设计模式

Laravel Controller Pattern:
In the App\Http\Controllers\Api namespace, create a UserController extending Controller. Import StoreUserRequest, UserResource, User, and JsonResponse. Define a store method accepting StoreUserRequest that creates a User using validated data and returns a JsonResponse with UserResource wrapping the user and status 201.
Laravel Form Request Pattern:
In the App\Http\Requests namespace, create a StoreUserRequest extending FormRequest. The authorize method returns true. The rules method returns an array with name requiring required, string, and max 255 validation, email requiring required, email, and unique on users table, and password requiring required, min 8, and confirmed validation.
Symfony Controller Pattern:
In the App\Controller namespace, create a UserController extending AbstractController. Import User, EntityManagerInterface, JsonResponse, and Route attribute. Apply Route attribute at class level for api/users path. Create a create method with Route attribute for empty path and POST method. Inject EntityManagerInterface, create new User, persist and flush, then return json response with user and status 201.

Laravel控制器模式:
在App\Http\Controllers\Api命名空间下,创建继承自Controller的UserController。导入StoreUserRequest、UserResource、User和JsonResponse。定义一个接收StoreUserRequest的store方法,使用验证后的数据创建User,并返回包裹UserResource的JsonResponse,状态码为201。
Laravel表单请求模式:
在App\Http\Requests命名空间下,创建继承自FormRequest的StoreUserRequest。authorize方法返回true。rules方法返回一个数组,其中name字段要求必填、字符串类型且最大长度255,email字段要求必填、邮箱格式且在users表中唯一,password字段要求必填、最小长度8且需确认。
Symfony控制器模式:
在App\Controller命名空间下,创建继承自AbstractController的UserController。导入User、EntityManagerInterface、JsonResponse和Route注解。在类级别应用Route注解,路径为api/users。创建一个带有Route注解的create方法,路径为空,请求方法为POST。注入EntityManagerInterface,创建新的User对象,执行persist和flush操作,然后返回包含用户信息的json响应,状态码为201。

Implementation Guide (5 minutes)

实施指南(5分钟)

PHP 8.3 Modern Features

PHP 8.3现代特性

Readonly Classes:
Declare a readonly class UserDTO with a constructor promoting public properties for int id, string name, and string email.
Enums with Methods:
Create an OrderStatus enum backed by string. Define cases Pending with pending value, Processing with processing value, and Completed with completed value. Add a label method that uses match expression on $this to return appropriate display labels for each case.
Attributes:
Create a Validate attribute class targeting properties with Attribute attribute. The constructor accepts a string rule and optional string message. Create a UserRequest class with email property decorated with Validate attribute specifying required and email rules.
只读类:
声明一个只读类UserDTO,通过构造函数提升属性,包含int类型的id、string类型的name和string类型的email。
带方法的枚举:
创建一个基于字符串的OrderStatus枚举。定义Pending(值为pending)、Processing(值为processing)和Completed(值为completed)三个枚举项。添加一个label方法,使用match表达式根据当前枚举项返回对应的显示标签。
注解:
创建一个Validate注解类,使用Attribute注解标记其作用于属性。构造函数接收一个字符串类型的规则和可选的字符串类型提示信息。创建一个UserRequest类,其email属性使用Validate注解标记,指定必填和邮箱格式规则。

Laravel 11 Patterns

Laravel 11设计模式

Eloquent Model with Relationships:
In the App\Models namespace, create a Post model extending Model. Set protected fillable array with title, content, user_id, and status. Set protected casts array with status casting to PostStatus enum and published_at casting to datetime. Define a user method returning BelongsTo relationship. Define a comments method returning HasMany relationship. Add a scopePublished method that filters by published status.
API Resource Pattern:
In the App\Http\Resources namespace, create a PostResource extending JsonResource. The toArray method takes a Request parameter. Return an array with id, title, author using UserResource with whenLoaded for user relationship, comments_count using whenCounted, and created_at formatted as ISO 8601 string.
Migration Pattern:
Create an anonymous migration class extending Migration. The up method calls Schema create on posts table. Define id, foreignId for user_id with constrained and cascadeOnDelete, string for title, text for content, string for status defaulting to draft, timestamps, and softDeletes.
Service Layer Pattern:
In the App\Services namespace, create a UserService class. Define a create method accepting UserDTO. Use DB transaction wrapping User create with data from DTO properties, profile creation with default bio, and returning user with loaded profile relationship. Catch ActiveRecord\RecordInvalid exceptions to handle validation failures.
带关联关系的Eloquent模型:
在App\Models命名空间下,创建继承自Model的Post模型。设置protected fillable数组包含title、content、user_id和status。设置protected casts数组,将status转换为PostStatus枚举,将published_at转换为datetime类型。定义一个user方法,返回BelongsTo关联关系。定义一个comments方法,返回HasMany关联关系。添加一个scopePublished方法,用于筛选已发布状态的内容。
API资源模式:
在App\Http\Resources命名空间下,创建继承自JsonResource的PostResource。toArray方法接收一个Request参数。返回一个包含id、title、author(使用UserResource并通过whenLoaded加载user关联)、comments_count(使用whenCounted)和格式化为ISO 8601字符串的created_at的数组。
迁移模式:
创建一个匿名的迁移类,继承自Migration。up方法调用Schema的create方法创建posts表。定义id字段、关联user_id的foreignId(带constrained和cascadeOnDelete)、string类型的title、text类型的content、默认值为draft的string类型的status、timestamps和softDeletes。
服务层模式:
在App\Services命名空间下,创建UserService类。定义一个接收UserDTO的create方法。使用DB事务包裹User创建操作(使用DTO属性的数据)、默认简介的profile创建操作,并返回加载了profile关联的用户。捕获ActiveRecord\RecordInvalid异常以处理验证失败。

Symfony 7 Patterns

Symfony 7设计模式

Entity with Doctrine Attributes:
In the App\Entity namespace, create a User class. Apply ORM\Entity attribute with repositoryClass pointing to UserRepository. Apply ORM\Table attribute with name users. Add private nullable int id with ORM\Id, ORM\GeneratedValue, and ORM\Column attributes. Add private nullable string name with ORM\Column length 255 and Assert\NotBlank. Add private nullable string email with ORM\Column length 180 unique and Assert\Email.
Service with Dependency Injection:
In the App\Service namespace, create a UserService class. The constructor accepts readonly EntityManagerInterface and readonly UserPasswordHasherInterface via property promotion. Define createUser method taking email and password strings. Create new User, set email, hash password using the password hasher, persist with entity manager, flush, and return user.
带Doctrine注解的实体:
在App\Entity命名空间下,创建User类。应用ORM\Entity注解,指定repositoryClass为UserRepository。应用ORM\Table注解,表名为users。添加带ORM\Id、ORM\GeneratedValue和ORM\Column注解的私有可空int类型id。添加带ORM\Column(长度255)和Assert\NotBlank注解的私有可空string类型name。添加带ORM\Column(长度180且唯一)和Assert\Email注解的私有可空string类型email。
依赖注入的服务:
在App\Service命名空间下,创建UserService类。构造函数通过属性提升注入只读的EntityManagerInterface和只读的UserPasswordHasherInterface。定义一个接收email和password字符串的createUser方法。创建新的User对象,设置email,使用密码哈希器哈希密码,通过实体管理器执行persist和flush操作,然后返回用户。

Testing Patterns

测试模式

PHPUnit Feature Test for Laravel:
In Tests\Feature namespace, create UserApiTest extending TestCase with RefreshDatabase trait. The test_can_create_user method posts JSON to api/users with name, email, password, and password_confirmation. Assert status 201 and JSON structure with data containing id, name, and email. Assert database has users table with the email.
Pest Test for Laravel:
Use App\Models\User and Post. Create a test using it function for can create a post. Create user with factory. Call actingAs with user, post JSON to api/posts with title and content. Assert status 201 and expect Post count to be 1. Create second test for requires authentication that posts without authentication and asserts status 401.

Laravel的PHPUnit功能测试:
在Tests\Feature命名空间下,创建继承自TestCase并使用RefreshDatabase trait的UserApiTest。test_can_create_user方法向api/users发送包含name、email、password和password_confirmation的JSON请求。断言状态码为201,且JSON结构中的data包含id、name和email。断言数据库的users表中存在该邮箱。
Laravel的Pest测试:
引入App\Models\User和Post。使用it函数创建一个“可以创建文章”的测试。通过工厂创建用户。调用actingAs方法设置当前用户,向api/posts发送包含title和content的JSON请求。断言状态码为201,且Post的数量为1。创建第二个测试“需要身份验证”,未认证情况下发送请求并断言状态码为401。

Advanced Implementation (10+ minutes)

高级实施(10+分钟)

For comprehensive coverage including:
  • Production deployment patterns for Docker and Kubernetes
  • Advanced Eloquent patterns including observers, accessors, and mutators
  • Doctrine advanced mapping with embeddables and inheritance
  • Queue and job processing
  • Event-driven architecture
  • Caching strategies with Redis and Memcached
  • Security best practices following OWASP patterns
  • CI/CD integration patterns
See:
  • modules/advanced-patterns.md for complete advanced patterns guide

如需以下内容的全面覆盖:
  • Docker和Kubernetes的生产部署模式
  • 高级Eloquent模式,包括观察者、访问器和修改器
  • 带嵌入类和继承的Doctrine高级映射
  • 队列与任务处理
  • 事件驱动架构
  • Redis和Memcached的缓存策略
  • 遵循OWASP模式的安全最佳实践
  • CI/CD集成模式
请查看:
  • modules/advanced-patterns.md 获取完整的高级模式指南

Context7 Library Mappings

Context7库映射

  • laravel/framework for Laravel web framework
  • symfony/symfony for Symfony components and framework
  • doctrine/orm for Doctrine ORM for PHP
  • phpunit/phpunit for PHP testing framework
  • pestphp/pest for elegant PHP testing framework
  • laravel/sanctum for Laravel API authentication
  • laravel/horizon for Laravel queue dashboard

  • laravel/framework 对应Laravel Web框架
  • symfony/symfony 对应Symfony组件与框架
  • doctrine/orm 对应PHP的Doctrine ORM
  • phpunit/phpunit 对应PHP测试框架
  • pestphp/pest 对应优雅的PHP测试框架
  • laravel/sanctum 对应Laravel API身份验证
  • laravel/horizon 对应Laravel队列仪表盘

Works Well With

协同工具

  • moai-domain-backend for REST API and microservices architecture
  • moai-domain-database for SQL patterns and ORM optimization
  • moai-workflow-testing for DDD and testing strategies
  • moai-platform-deploy for Docker and deployment patterns
  • moai-essentials-debug for AI-powered debugging
  • moai-foundation-quality for TRUST 5 quality principles

  • moai-domain-backend:用于REST API和微服务架构
  • moai-domain-database:用于SQL模式和ORM优化
  • moai-workflow-testing:用于DDD和测试策略
  • moai-platform-deploy:用于Docker和部署模式
  • moai-essentials-debug:用于AI驱动的调试
  • moai-foundation-quality:用于TRUST 5质量原则

Troubleshooting

故障排除

Common Issues:
PHP Version Check:
Run php with version flag to verify 8.3 or later. Use php with -m flag piped to grep for checking pdo, mbstring, and openssl extensions.
Composer Autoload Issues:
Run composer dump-autoload with -o flag for optimized autoloader. Run composer clear-cache to clear the package cache.
Laravel Cache Issues:
Run php artisan config:clear to clear configuration cache. Run php artisan cache:clear to clear application cache. Run php artisan route:clear to clear route cache. Run php artisan view:clear to clear compiled views.
Symfony Cache Issues:
Run php bin/console cache:clear to clear cache. Run php bin/console cache:warmup to warm up the cache.
Database Connection:
Use try-catch block around DB::connection()->getPdo() call. Output success message on connection or exception message on failure.
Migration Rollback:
Use php artisan migrate:rollback with step 1 to rollback last migration. Use php artisan migrate:fresh with seed flag for development reset only. For Symfony, use php bin/console doctrine:migrations:migrate prev to rollback.

Version: 1.1.0 | Updated: 2026-01-11 | Status: Active
常见问题:
PHP版本检查:
运行带version参数的php命令验证版本为8.3或更高。运行带-m参数的php命令并通过grep检查pdo、mbstring和openssl扩展。
Composer自动加载问题:
运行composer dump-autoload -o生成优化的自动加载器。运行composer clear-cache清除包缓存。
Laravel缓存问题:
运行php artisan config:clear清除配置缓存。运行php artisan cache:clear清除应用缓存。运行php artisan route:clear清除路由缓存。运行php artisan view:clear清除编译后的视图。
Symfony缓存问题:
运行php bin/console cache:clear清除缓存。运行php bin/console cache:warmup预热缓存。
数据库连接:
在DB::connection()->getPdo()调用外包裹try-catch块。连接成功时输出成功信息,失败时输出异常信息。
回滚迁移:
运行php artisan migrate:rollback --step=1回滚最后一次迁移。仅在开发环境运行php artisan migrate:fresh --seed重置数据库。对于Symfony,运行php bin/console doctrine:migrations:migrate prev进行回滚。

版本:1.1.0 | 更新时间:2026-01-11 | 状态:活跃