php-rules

PHP 编码规范合集,涵盖风格、常用模式、安全性检查与测试实践。触发条件包括 .php 文件、composer.json、Laravel、Symfony、PHPUnit、PSR-12 或 Composer 相关项目文件。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "php-rules":https://skillpi.com/zh/skills/deepskill-896e8116bd168be220a1a3df44d6451910402f1a2da03714f643f5ed77b669be。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

PHP 编码规范合集,涵盖风格、常用模式、安全性检查与测试实践。触发条件包括 .php 文件、composer.json、Laravel、Symfony、PHPUnit、PSR-12 或 Composer 相关项目文件。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: php-rules
description: "PHP coding rules: style, patterns, security, testing. Triggers: .php, composer.json, Laravel, Symfony, PHPUnit, PSR-12, Composer."
effort: medium
user-invocable: false
allowed-tools: Read

PHP Rules

These rules come from app/rules/php/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in PHP. Apply them when writing or reviewing PHP code.

PHP Coding Style

Standards

  • Follow PSR-12 extended coding style.
  • Use declare(strict_types=1) at the top of every file.
  • Use PHP 8.1+ features: enums, fibers, readonly properties, intersection types.
  • Use PHP CS Fixer or Pint for automated formatting.

Naming

  • PascalCase: classes, interfaces, traits, enums.
  • camelCase: methods, functions, variables.
  • UPPER_SNAKE: class constants (public const MAX_RETRIES = 3).
  • snake_case: not used for methods. PSR convention is camelCase.
  • Suffix interfaces with Interface or prefix with contract name (project convention).

Type System

  • Use typed properties: private readonly string $name;.
  • Use union types: string|int. Use intersection types: Countable&Iterator.
  • Use enum (PHP 8.1) for fixed sets of values. Use backed enums for persistence.
  • Use readonly classes (PHP 8.2) for immutable DTOs.
  • Use constructor promotion: public function __construct(private string $name).
  • Use never return type for functions that throw or exit.

Functions

  • Use typed parameters and return types on all functions/methods.
  • Use named arguments for readability: new User(name: 'Ada', age: 36).
  • Use null-safe operator: $user?->address?->city.
  • Use match expression over switch for value mapping.
  • Use first-class callable syntax: array_map($this->transform(...), $items).

Imports and Namespaces

  • Use PSR-4 autoloading via Composer.
  • Group use statements: classes, functions, constants.
  • Never use require/include for class loading. Use Composer autoloader.
  • Use one class per file. File name matches class name.

Error Handling

  • Use exceptions for error conditions. Never return error codes.
  • Create domain exception hierarchies extending RuntimeException or LogicException.
  • Use match with throw for exhaustive error mapping.
  • Log exceptions with context using PSR-3 logger.

Configuration

  • Use PHPStan at level 8+ for static analysis.
  • Use Rector for automated code upgrades and refactoring.
  • Use .php-cs-fixer.dist.php for formatting rules.
  • Run composer analyse (PHPStan) and composer format (Pint) in CI.

PHP Frameworks

Laravel

  • Use route model binding: Route::get('/users/{user}', ...).
  • Use Form Requests for validation: class StoreUserRequest extends FormRequest.
  • Use Eloquent scopes for reusable query constraints: scopeActive().
  • Use API Resources for response transformation: UserResource::collection($users).
  • Use config() helper for configuration. Never access env() outside config files.
  • Use middleware groups for auth, throttling, and CORS.

Eloquent ORM

  • Use relationships: hasMany, belongsTo, belongsToMany, morphMany.
  • Use eager loading: User::with('posts.comments')->get() to prevent N+1.
  • Use $fillable or $guarded on models. Prefer $fillable (explicit whitelist).
  • Use model events or observers for lifecycle hooks.
  • Use upsert() for bulk insert-or-update operations.
  • Use cursor() for memory-efficient iteration over large result sets.

Symfony

  • Use attributes for route definitions: #[Route('/api/users', methods: ['GET'])].
  • Use autowiring for dependency injection. Register services in services.yaml.
  • Use Symfony Forms for complex validation and data mapping.
  • Use Messenger component for async message handling (commands, events).
  • Use Doctrine ORM with repository pattern and query builders.

Doctrine ORM

  • Use entity classes with annotations or attributes for mapping.
  • Use repositories for data access: $em->getRepository(User::class).
  • Use DQL for type-safe queries. Use QueryBuilder for dynamic queries.
  • Use migrations: bin/console doctrine:migrations:diff and migrate.
  • Use lifecycle callbacks (@PrePersist, @PostUpdate) for entity events.

Symfony Serializer

  • Default behavior uses property names as-is. Combined with PSR-12 camelCase property names, JSON output is camelCase with zero configuration.
  • Avoid adding api_platform.name_converter: CamelCaseToSnakeCaseNameConverter globally. Known side-effect (api-platform/core #6101): overrides the project-wide MetadataAwareNameConverter, affecting Messenger serializers, custom normalizers, and CLI JSON output — not just the HTTP API.
  • Use #[SerializedName] only when justified: legacy field alias during rename, external contract mapping, ObjectNormalizer cross-version stabilization. Community practice (Symfony docs, Sylius, SymfonyCasts): prefer clean property/getter naming over aliases. When using, document the reason next to the attribute.
  • Symfony 7.3.5+ ObjectNormalizer produces isActive natively for a isActive(): bool getter (symfony/symfony #62353). Older #[SerializedName('isActive')] aliases added for pre-7.3.5 ObjectNormalizer (which produced active) are redundant after upgrade — remove them.
  • Avoid duplicate getters like isActive() + getIsActive() on the same property — ObjectNormalizer treats them as two fields and serializes ambiguously. Keep one (isXxx() for booleans, getXxx() otherwise).

API Platform

  • Use API Platform for rapid REST/GraphQL API generation from entities.
  • Use #[ApiResource] attribute for automatic CRUD endpoint generation.
  • Use custom state providers and processors for business logic.
  • Use serialization groups for controlling response shape.
  • Use filters for query parameter support: pagination, search, ordering.
  • Property names on ApiResource DTOs drive JSON keys directly (see Symfony Serializer above). Write them in camelCase — that is both the Symfony default and the dominant JSON API convention.
  • Use operation_name in extraProperties for dispatch metadata (e.g., extraProperties: ['operation_name' => 'club_activate']). The key operation_name and its snake_case values are framework metadata, not JSON wire keys — keeping them snake_case is expected.

Livewire (Laravel)

  • Use Livewire components for reactive UI without JavaScript.
  • Use wire:model for two-way data binding on form inputs.
  • Use $rules property for inline validation on component properties.
  • Use component actions for server-side event handling.
  • Use wire:loading for loading state indicators.

Queues and Workers

  • Use Laravel Horizon for Redis queue monitoring and management.
  • Use Symfony Messenger with transports (Redis, AMQP, Doctrine).
  • Use dead letter queues for failed job inspection and replay.
  • Use rate limiting on queue workers to prevent downstream overload.

PHP Patterns

Error Handling

  • Use custom exception hierarchies: class DomainException extends RuntimeException.
  • Add context to exceptions: throw new UserNotFoundException(userId: $id).
  • Use match with default => throw for exhaustive error mapping.
  • Use set_exception_handler() for global uncaught exception handling.
  • Log exceptions with PSR-3 logger and structured context.

Enums and Value Objects

  • Use backed enums for database-persisted values: enum Status: string.
  • Use from() for strict conversion, tryFrom() for nullable safe conversion.
  • Implement methods on enums for behavior: public function label(): string.
  • Use readonly classes for value objects: readonly class Money { ... }.
  • Use constructor promotion for concise value object definitions.

Repository Pattern

  • Abstract data access behind repository interfaces.
  • Repositories return domain entities, not Eloquent models or arrays.
  • Use constructor injection for repository dependencies.
  • Use specifications or criteria objects for complex query building.
  • Keep repository methods focused: one query per method.

Service Layer

  • Use service classes for business logic. Keep controllers thin.
  • Use action classes (single-method services) for discrete operations.
  • Use DTOs for data transfer between layers. Never pass request objects to services.
  • Use command/query separation: commands mutate, queries read.
  • Inject dependencies via constructor. Never use app() helper in services.

Collections and Iterators

  • Use Laravel Collections or standalone illuminate/collections for data manipulation.
  • Chain map(), filter(), reduce() for declarative data transformation.
  • Use LazyCollection for memory-efficient processing of large datasets.
  • Use generators (yield) for lazy iteration over large result sets.
  • Prefer collect() pipeline over nested loops.

Async Patterns

  • Use Laravel Queues for background job processing.
  • Use dispatch() for fire-and-forget. Use Bus::chain() for sequential jobs.
  • Use ShouldQueue interface on jobs, listeners, and mailables.
  • Set $tries, $timeout, $backoff on job classes.
  • Use batch() for parallel job execution with completion callback.

Event-Driven

  • Use events and listeners for decoupled side effects.
  • Use domain events for cross-boundary communication.
  • Use ShouldQueue on listeners for async event handling.
  • Use event subscribers for grouping related listeners.
  • Keep event payloads minimal: IDs and timestamps, not full objects.

Anti-Patterns

  • Fat controllers: move logic to services/actions.
  • God models: split into focused models with traits or separate classes.
  • Using DB::raw() without parameterization: SQL injection risk.
  • Static method calls for testable dependencies: use DI instead.
  • Returning mixed types: use typed returns or Result objects.

PHP Security

SQL Injection

  • Use PDO prepared statements with bound parameters for all queries.
  • Use Eloquent/Doctrine ORM for type-safe query building.
  • Never concatenate user input into SQL strings. Never use DB::raw($input).
  • Use whereIn() with arrays, not string interpolation for IN clauses.
  • Audit raw queries: DB::select(DB::raw(...)) must use ? placeholders.

XSS Prevention

  • Blade templates auto-escape with {{ }}. Never use {!! !!} with user data.
  • Use htmlspecialchars() with ENT_QUOTES when outputting outside Blade.
  • Set Content-Security-Policy headers to restrict inline scripts.
  • Sanitize rich-text input with HTMLPurifier before storage.
  • Use strip_tags() only as a secondary measure, not primary defense.

CSRF Protection

  • Use @csrf directive in all Blade forms.
  • Use VerifyCsrfToken middleware (enabled by default in Laravel).
  • Use X-CSRF-TOKEN header for AJAX requests from SPA frontends.
  • Exclude only webhook endpoints from CSRF verification (with careful validation).

Authentication

  • Use password_hash() with PASSWORD_ARGON2ID or PASSWORD_BCRYPT.
  • Use Laravel Sanctum for SPA/mobile API authentication.
  • Use Laravel Passport for full OAuth2 server implementation.
  • Implement rate limiting on login endpoints: ThrottleRequests middleware.
  • Use multi-factor authentication for admin accounts.

Authorization

  • Use Laravel Gates and Policies for authorization logic.
  • Use $this->authorize('update', $post) in controllers.
  • Check resource ownership in policies, not just role membership.
  • Default deny: use Gate::before() for super-admin bypass, nothing else.
  • Use middleware can:permission for route-level authorization.

File Upload

  • Validate file MIME type server-side. Do not trust Content-Type header.
  • Store uploads outside the web root. Use storage/ with Storage::disk().
  • Generate random filenames. Never use original user-provided filenames.
  • Set maximum file size limits in validation and PHP upload_max_filesize.
  • Scan uploaded files for malware in production environments.

Mass Assignment

  • Use $fillable on Eloquent models. Never use $guarded = [].
  • Use Form Requests to whitelist fields before model assignment.
  • Use DTOs for data transfer. Never pass $request->all() to create().
  • Audit forceFill() and forceCreate() usage (bypasses guarding).

Secrets and Configuration

  • Use .env files for local secrets. Use Vault or SSM for production.
  • Never commit .env to version control. Commit .env.example as template.
  • Use config() helper, never env() outside of config files (caching issue).
  • Never log request content containing passwords or tokens.
  • Use APP_DEBUG=false in production. Debug mode leaks sensitive data.

PHP Testing

Framework

  • Use PHPUnit 10+ as the primary test framework.
  • Use Pest PHP for expressive, minimal-boilerplate testing (built on PHPUnit).
  • Use Mockery for flexible mocking. Use PHPUnit built-in mocks for simple cases.
  • Use Testcontainers (via Docker) for integration tests with databases.

File Naming

  • Test files: FooTest.php in tests/ mirroring src/ namespace structure.
  • Unit tests: tests/Unit/. Integration tests: tests/Integration/ or tests/Feature/.
  • PHPUnit config: phpunit.xml.dist at project root.
  • Use @group annotations for test categorization.

Structure (PHPUnit)

  • Use #[Test] attribute (PHP 8) or test prefix for test methods.
  • Use setUp() / tearDown() for per-test initialization and cleanup.
  • Use #[DataProvider('dataMethodName')] for parameterized tests.
  • Name tests: testMethodName_Scenario_ExpectedResult or descriptive snake_case.

Structure (Pest)

  • Use test('description', function () { ... }) for test cases.
  • Use it('should do something', ...) for BDD-style descriptions.
  • Use beforeEach() / afterEach() for setup and teardown.
  • Use dataset() for shared test data across multiple tests.
  • Use ->with([...]) for inline parameterized tests.

Assertions

  • Use $this->assertSame() for strict equality (type + value).
  • Use $this->assertInstanceOf(Foo::class, $result) for type checks.
  • Use $this->expectException(FooException::class) before the throwing call.
  • Use $this->assertCount(), $this->assertContains() for collections.
  • Pest: use expect($value)->toBe(), ->toBeInstanceOf(), ->toThrow().

Mocking (Mockery)

  • Create mocks: $mock = Mockery::mock(UserRepository::class).
  • Stub: $mock->shouldReceive('find')->with(1)->andReturn($user).
  • Verify: $mock->shouldHaveReceived('save')->once().
  • Use Mockery::close() in tearDown() or afterEach().
  • Use spy() to verify interactions without stubbing.

Laravel Testing

  • Use RefreshDatabase trait for database test isolation.
  • Use $this->actingAs($user) for authenticated request testing.
  • Use $this->getJson('/api/users')->assertOk()->assertJsonCount(3).
  • Use factories: User::factory()->create() for test data.
  • Use Bus::fake(), Event::fake(), Mail::fake() for side-effect assertion.

Best Practices

  • Test behavior, not implementation. Do not test private methods.
  • Use in-memory SQLite for fast database tests when schema is compatible.
  • Run php artisan test --parallel for faster Laravel test execution.
  • Use --coverage-html for visual coverage reports.
  • Keep tests fast: mock external HTTP calls with Http::fake().

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值95/100

亮点

  • 提供全面的 PHP 编码规范,涵盖风格、框架、安全、测试等核心领域
  • 对 PHP 开发者具有高频刚需价值,显著提升代码质量和开发效率
触发精准90/100

亮点

  • 触发条件明确且完整,覆盖 .php、composer.json、Laravel、Symfony 等关键标识
结构规范95/100

亮点

  • 文档结构清晰,分章节组织,每部分有具体子条目和示例
  • frontmatter 完整,单文件长度适中,易于阅读和维护
执行可靠90/100

待提升项

  • description写错位置 原报告严重程度:轻微

    顶层 frontmatter 中 description 为空,实际描述内容位于 skill_body 内部

    改进建议:将 description 内容移至顶层 frontmatter 中,确保元数据完整性和一致性

亮点

  • 内容为静态规范文档,无动态执行风险
  • 推荐的工具来源明确,参数建议合理,具备高度可靠性
证据可验 (前四项均值)93/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • github.com
  • symfony.com

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。