360 Secure SkillHub
360 安全技能中心

laravel-clean-pattern

提供 Laravel 12+/PHP 8.3+ 项目的模块化洁净架构蓝图,涵盖 SOLID 与设计模式、五层精简控制器流程、en/ar 本地化、Day-1 安全中间件与 AES-256-GCM 响应加密,并附带三个 Node 审计脚本用于检查控制器、响应与翻译一致性。

分类:开发
yahongie2014
yahongie2014
热度 30.80
最近更新 2026-12-03 13:00:30

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add yahongie2014/laravel-clean-pattern
兼容性
通用兼容
联网要求
需要联网
数据出网
可选出网
Metadata
name
laravel-clean-pattern
description
Universal Laravel 12+ Clean Architecture master skill for creating any new project or refactoring existing APIs. Grounded in SOLID principles and Design Patterns (Repository, Strategy, Decorator, Pipeline, Action, DTO, Events), with Day-1 security bootstrap, centralized API responses, EN/AR i18n, Backed Enums, FormRequests, API Resources, N+1 prevention, security middleware, AES-256-GCM response encryption, and Postman collections.

Laravel Clean Pattern — Universal Master Skill

A single, project-agnostic production architecture playbook for creating any new Laravel 12+ / PHP 8.3+ project (SaaS, E-Commerce, Marketplace, Booking, Fintech, Mobile/SPA API) or refactoring existing backends. Enforces SOLID principles, pragmatic Design Patterns, thin controllers, typed contracts, zero N+1 queries, full en/ar multi-language localization, Day-1 security hardening, AES-256-GCM response encryption, and automated Postman collections.


0. Creating Any New Laravel Project (Single-Module Architecture Bootstrap)

Whenever starting a brand-new Laravel project, split every business domain into its own self-contained single module under app/Modules/<ModuleName>/, and keep only cross-cutting infrastructure in app/Shared/:

  1. Scaffold & Guard:
    • Initialize Laravel (composer create-project laravel/laravel <project-name>).
    • Keep .env out of Git, maintain placeholder-only .env.example, and enable Model::preventLazyLoading(! app()->isProduction()) in AppServiceProvider::boot().
  2. Create the Modular Folder Skeleton (app/Shared/ + app/Modules/<ModuleName>/):
    app/
    ├── Shared/                                   # Cross-cutting infrastructure only (no business domain)
    │   ├── Http/
    │   │   ├── Controllers/BaseController.php    # Centralized ApiResponse JSON helpers
    │   │   └── Middleware/                       # SetAppLocale, SecurityHeaders, EncryptBrowserResponses
    │   ├── Services/BrowserResponseCrypto.php    # Shared AES-256-GCM transport crypto
    │   ├── Support/ApiResponse.php               # Unified { success, message, data } builder
    │   └── ValueObjects/Money.php                # Shared immutable Value Objects
    └── Modules/
        └── <ModuleName>/                         # e.g. Auth, Users, Catalog, Orders, Billing
            ├── Providers/<ModuleName>ServiceProvider.php  # Binds contracts, routes, migrations, lang
            ├── Routes/api.php                    # Module-scoped routes (/api/v1/<module>)
            ├── Http/
            │   ├── Controllers/                  # Thin HTTP orchestrators only
            │   ├── Requests/                     # FormRequests (prepareForValidation & toDto)
            │   └── Resources/                    # Typed JsonResources (whenLoaded / whenCounted)
            ├── Actions/                          # Multi-repository single-use invokable use cases
            ├── Data/                             # Immutable final readonly DTOs
            ├── Enums/                            # PHP 8.1+ Backed Enums with localized label()
            ├── Events/                           # Domain events & PrivateChannel broadcasts
            ├── Listeners/                        # Queued listeners reacting to other modules' events
            ├── Models/                           # Eloquent models with explicit $fillable & casts()
            ├── Policies/                         # Authorization & ownership (IDOR prevention)
            ├── Repositories/
            │   ├── Contracts/                    # Segregated *RepositoryInterface contracts
            │   └── *Repository.php               # Eloquent queries, transactions & lockForUpdate
            ├── Services/                         # Cohesive domain services (scoped caching, Strategy/Decorator)
            ├── Database/
            │   ├── Migrations/                   # Module-owned migrations (loaded by provider)
            │   └── Factories/                    # Module model factories
            └── Lang/
                ├── en/messages.php               # Module EN translations (100% parity with ar)
                └── ar/messages.php               # Module AR translations (100% parity with en)
    lang/
    ├── en/messages.php                           # Shared/global EN messages
    └── ar/                                       # Shared/global AR messages & validation.php
    postman/
    └── <project>.postman_collection.json         # Auto-maintained v2.1.0 API collection
    
  3. Plug-and-Play Insert / Eject Modules (Clean Repository Pattern):
    • Auto-Discovery (App\Shared\Providers\ModuleRegistryProvider): Register ModuleRegistryProvider once in bootstrap/providers.php to auto-discover every app/Modules/<Module>/Providers/<Module>ServiceProvider.php (respecting config/modules.php enable/disable toggles).
    • Self-Contained Module Ownership: Each <Module>ServiceProvider owns 100% of its Repositories/Contracts/*Interface → *Repository bindings, Config/<module>.php (mergeConfigFrom), Policies (Gate::policy), Routes/api.php, Database/Migrations, Lang/{en,ar} (__('orders::messages.*')), and Event::listen(...) subscriptions. Never edit global files to wire a module.
    • Zero-Friction Insert & Eject:
      • Insert: Drop app/Modules/<NewModule>/ into app/Modules/ → repositories, routes, migrations, translations, policies, and listeners activate automatically.
      • Eject: Delete app/Modules/<Module>/ (or toggle it false in config/modules.php) → zero broken imports, routes, migrations, or DI bindings anywhere else in the app.
    • Zero Cross-Module Model Leaks: Module A NEVER queries Module B's Eloquent Model directly or adds hard DB foreign keys into an ejectable module's tables. Cross-module interaction goes ONLY through:
      • Shared Contracts + Null Object Fallback (app/Shared/Contracts/*Interface with a safe no-op default bound in ModuleRegistryProvider, overridden when the target module is inserted), OR
      • Domain Events + module-local queued Listeners (Observer/Pub-Sub).
    • Blueprint: ModuleServiceProviderTemplate.php.
  4. Wire Global Middleware & Day-1 Security:
    • Register in bootstrap/app.php: trustProxies(at: '*') → SetAppLocale → SecurityHeaders → (optional) EncryptBrowserResponses.
    • Lock down config/cors.php, secure session cookies, RateLimiter rules, Policies/ownership checks, upload validation, and composer audit (see Section 6).
  5. Build & Verify: Build every feature inside its module with SOLID + Design Patterns + 5-Layer Clean Pattern + en/ar translations + Postman collection updates + automated audits.

1. SOLID Principles & Design Patterns

Every Laravel feature, service, repository, and refactor MUST follow SOLID and select the right pattern without speculative over-abstraction:

SOLID in Laravel

  • S — Single Responsibility (SRP): One reason to change per class — FormRequest (normalize & validate), Controller (HTTP orchestration), Repository (persistence/queries/transactions), Service / Action (domain workflow), JsonResource (serialization). Never build "God" controllers, models, or services.
  • O — Open/Closed (OCP): Extend varying behaviors (payment gateways, pricing tiers, notification channels, exporters, filter pipelines) via interfaces + Strategy, Decorator, or Laravel Pipeline bindings instead of growing if/elseif or switch chains.
  • L — Liskov Substitution (LSP): Every implementation of a contract MUST honor parameter types, return types, nullability, and exceptions. Never branch on concrete types with instanceof or throw "not supported" stubs.
  • I — Interface Segregation (ISP): Prefer small, role-focused contracts (e.g., splitting ReaderInterface / WriterInterface) over fat multi-domain interfaces.
  • D — Dependency Inversion (DIP): High-level controllers and services depend on Contracts\*Interface via private readonly constructor promotion, bound in AppServiceProvider::register(). Avoid Service Locator (app(...)) inside domain logic.

Core Design Patterns Selection Matrix

Scenario Pattern SOLID
Persistence & transactions Repository (app/Repositories/Contracts/*Interface.php) SRP, DIP
Swappable algorithms/providers Strategy + $this->app->tag([...]) Resolver OCP, DIP
Caching/logging around a repo Decorator wrapping *Interface SRP, OCP
Multi-step filtering/checkout Pipeline (Illuminate\Pipeline\Pipeline) SRP, OCP
Decoupled side effects Observer / Events (DB::afterCommit + queued Job) SRP, OCP
Multi-repo single use case Action (final readonly class in app/Actions/) SRP
Typed inputs & invariants Readonly DTO (FormRequest::toDto()) & Value Object (Money) SRP, LSP
Fat interface with unused methods Segregated Interfaces ISP, LSP

2. 5-Layer Clean Architecture & Repository Pattern

Every backend feature flows through 5 strict layers:

  1. FormRequest (app/Http/Requests/**) — Input normalization & validation.
  2. Thin Controller (app/Http/Controllers/**) — HTTP orchestration only.
  3. Repository (app/Repositories/Contracts/*Interface.php + app/Repositories/*Repository.php) — Persistence, eager loading, and locking.
  4. Reusable Services & Actions (app/Services/*Service.php, app/Actions/*Action.php) — Cohesive domain logic & caching.
  5. API Resource & Response (app/Http/Resources/*Resource.php + App\Support\ApiResponse) — Typed JSON contracts.

Repository Rules

  • Bind every interface in AppServiceProvider::register(): $this->app->bind(DomainRepositoryInterface::class, DomainRepository::class);.
  • NEVER call Model::query(), Model::where(), Model::find(), Model::create(), DB::transaction(), or Schema::hasTable() inside any controller.
  • Wrap multi-step state transitions in DB::transaction(...) with ->lockForUpdate() inside the repository and return structured results (['code' => 200, 'model' => $m] or ['code' => 422, 'message' => __('messages.*')]).
  • Blueprint: RepositoryTemplate.php

3. Centralized API Responses & Full Multi-Language Translation (Default en / ar)

Centralized JSON Responses

All endpoints MUST return JSON through App\Support\ApiResponse (ApiResponse.php) and base Controller helpers:

  • jsonSuccess(mixed $data = null, ?string $message = null, int $status = 200, array $extra = [], bool $includeData = true)
  • jsonCreated(mixed $data = null, ?string $message = null, array $extra = [])
  • jsonOk(array $payload = [], int $status = 200)
  • jsonError(string $message, int $status = 422, mixed $data = null, array $extra = [])
  • jsonUnauthorized(...) / jsonForbidden(...) / jsonNotFound(...)
  • 0 raw response()->json() calls in app/Http/Controllers/** and app/Services/**.

Full Multi-Language Policy (Default en / ar)

  • Every project MUST ship with en (LTR fallback) and ar (RTL) fully translated in lang/en/messages.php, lang/ar/messages.php, and lang/ar/validation.php.
  • NEVER hardcode user-facing English or Arabic strings in Controllers, Services, Repositories, FormRequests (messages()/attributes()), API Resources, Backed Enum label() methods, Notifications, Mailables, or Exceptions — always use __('messages.<key>', [...]).
  • Maintain 100% key & placeholder parity (:name, :count, :seconds) across en and ar (and any additional locales), verified with audit-translations.cjs.

4. Backed Enums, FormRequests & API Resources

Backed Enums (app/Enums/)

  • Use PHP 8.1+ Backed Enums (enum Status: string, enum PriceTier: int) instead of magic strings.
  • Provide localized label(): string (__('messages.*')), color(): string, icon(): string, options(): array, and safe fromCode(?string $code): ?self (strtoupper(trim(...)) + self::tryFrom(...)).
  • For live API-updated values (e.g., Currency::exchangeRate()), delegate to a request-scoped service (app(ExchangeRateService::class)->rateFor($this->value)) while keeping a terminal static fallback (defaultRate(): float) to prevent circular recursion.
  • Cast enum columns in Eloquent casts() and validate inputs with Rule::enum(MyEnum::class).

FormRequests (app/Http/Requests/**)

  • Never call $request->validate(...) inline in controllers.
  • Normalize inputs in prepareForValidation() (trim strings, lowercase emails, uppercase codes, strip non-digits from OTPs).
  • Use array syntax for rules (['required', 'string', 'min:8', 'confirmed', 'different:current_password']).
  • For bearer-token routes, resolve the user in authorize() and expose authenticatedUser(): User (and optional toDto()).

API Resources (app/Http/Resources/*Resource.php)

  • Never return raw Eloquent models directly.
  • Cast scalars explicitly ((int), (float), (bool), ?string) and format dates with ->toIso8601String().
  • Always use $this->whenLoaded('relation', ...) and $this->whenCounted('items') to prevent lazy-loading N+1 queries.
  • Guard private fields (payment handles, tokens, credentials) with $this->when($isOwner, ...) or $this->mergeWhen(...).

5. Events, Reusable Services, Scoped Caching & N+1 Prevention

Events & Real-Time Broadcasting (app/Events/)

  • Use ShouldBroadcastNow for latency-sensitive UI updates (chat, notifications, presence) or ShouldBroadcast for queued fan-out.
  • Define explicit broadcastAs(): string and minimal broadcastWith(): array payloads on PrivateChannel('user.' . $recipientId) authorized in routes/channels.php.
  • Wrap non-critical broadcasts in try { event(...); } catch (Throwable $e) { Log::warning(...); } so socket outages never break HTTP writes.
  • Keep Model::saved / Model::created hooks non-blocking: check $model->wasRecentlyCreated || $model->wasChanged([...]) and dispatch queued jobs guarded by Cache::add($lockKey, true, $ttl).

Reusable Services & N+1 Prevention (app/Services/)

  • Enforce Model::preventLazyLoading(! app()->isProduction()) in AppServiceProvider::boot().
  • Eager-load relations with explicit columns (->with(['owner:id,name'])) and counts (->withCount('items as items_count')).
  • Batch cache reads with Cache::many($keys) and bulk DB lookups with whereIn(...)->get()->keyBy('id').
  • Chunk bulk writes via upsert() or array_chunk($rows, 100).

Request-Scoped Caching & Persistent Snapshots

  • Bind read-heavy config/rate services with $this->app->scoped(MyService::class).
  • Memoize config & snapshots in instance properties per request, and provide flushMemoryCache(bool $syncContainer = true) on writes to keep container instances in sync.
  • Persist critical external API snapshots to both Cache and DB (app_configs) so live data survives cache:clear, with a cooldown-guarded lazy fetch on first miss outside unit tests.
  • Blueprint: ScopedSnapshotService.php

6. Auth Security, Middleware Stack & Encrypted Browser Responses

Global Middleware Order (bootstrap/app.php)

Register middlewares in this exact order:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->trustProxies(at: '*');
    $middleware->append(SetAppLocale::class);
    $middleware->append(SecurityHeaders::class);
    $middleware->append(EncryptBrowserResponses::class);
})
  • SetAppLocale: Resolve locale deterministically (X-App-Locale header → ?lang= query → Accept-Language → 'en'), strictly whitelisting supported locales before app()->setLocale($locale).
  • SecurityHeaders: Set X-Frame-Options: SAMEORIGIN, X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy: camera=(), microphone=(), geolocation=(), and emit Strict-Transport-Security: max-age=31536000; includeSubDomains ONLY when $request->isSecure().
  • EncryptBrowserResponses + BrowserResponseCrypto (AES-256-GCM):
    • issueBrowserBundle() generates a 32-byte ephemeral AES key + TTL-bound Crypt::encryptString X-Transport-Token.
    • On opt-in requests (X-Encrypted-Response: 1 + valid X-Transport-Token), encrypt JSON bodies with aes-256-gcm (base64(12B IV || ciphertext || 16B tag)), preserve headers/cookies, set Content-Type: application/octet-stream, X-Response-Encrypted: 1, Cache-Control: no-store, no-cache, must-revalidate, private, and Vary: X-Encrypted-Response.
    • Skip admin*, livewire*, Telescope path, BinaryFileResponse, StreamedResponse, 204, empty, and non-JSON responses.
    • Application-layer payload encryption is defense-in-depth and never replaces HTTPS/TLS, authentication, or authorization.
  • Blueprint: MiddlewareSecurityLocaleCrypto.php

Auth Security Hardening (config/auth_security.php, AuthSecurityService)

  • Track login/OTP failures across all linked identifiers simultaneously (user_id, normalized phone, lowercased email).
  • Escalate progressively: CAPTCHA challenge (turnstile/hcaptcha/recaptcha/log) → 429 lockout with Retry-After.
  • Layer RateLimiter rules in AppServiceProvider: per-IP + per-normalized-phone limits (10/min/IP + 5/min & 20/hr per phone).
  • Authenticated password changes (PATCH /api/v1/auth/password) verify Hash::check($current, $user->password) and throttle with auth-login.

New Project Security Checklist (Apply on Day 1)

When bootstrapping any new Laravel project, enforce these baseline security controls immediately:

  1. Secrets & Environment: Never commit .env or private keys; keep .env.example placeholder-only; enforce APP_DEBUG=false in production; gate debug tools (Telescope, Horizon) behind non-guessable paths and admin auth.
  2. Mass Assignment & SQLi: Define explicit $fillable on every model (never $guarded = [] on user-editable models); pass only $request->validated() or typed DTOs; never interpolate user input into DB::raw() / whereRaw() / orderByRaw() — bind parameters and whitelist sort columns.
  3. IDOR & Authorization: Enforce Policies (Gate::authorize(...)) or explicit ownership checks ($model->isOwnedBy($user)) on every read/write of user-owned records; consider ULIDs/UUIDs for public resource IDs.
  4. CORS & Cookies: Never combine allowed_origins => ['*'] with supports_credentials => true in config/cors.php; whitelist exact frontend origins and set SESSION_SECURE_COOKIE=true, http_only=true, same_site=lax, SESSION_ENCRYPT=true.
  5. File Uploads & SSRF: Validate uploads by MIME + extension + max size, store with random Str::uuid() names on private/non-executable disks; restrict outbound HTTP calls to https:// allowlisted hosts (blocking loopback/private metadata IPs like 127.0.0.1 and 169.254.169.254).
  6. Dependency & Token Hygiene: Run composer audit (and npm audit if frontend exists); revoke old tokens on password change/reset; never leak account existence on forgot-password endpoints.

7. Postman Collection (API Projects) & Local Composer Packages

Postman Collection v2.1.0 (postman/<project-slug>.postman_collection.json)

Whenever a project exposes endpoints in routes/api.php:

  • Create and maintain a valid Postman v2.1.0 collection grouped by domain/controller.
  • Define collection variables: base_url, api_prefix, token, locale (en/ar).
  • Set collection-level bearer auth ({{token}}), override with noauth on public routes, and include Accept: application/json + X-App-Locale: {{locale}}.
  • Match request JSON bodies and query/path params to each FormRequest, attach a post-response test script on Login/Register to auto-save pm.collectionVariables.set('token', ...), and update the collection whenever API routes or contracts change.
  • Blueprint: postman_collection.template.json

First-Party Local Composer Packages (packages/<vendor>/<name>)

  • Extract owned or unmaintained dependencies into packages/<vendor>/<name>/ with PSR-4 autoloading, extra.laravel.providers, and a root composer.json path repository ("symlink": true), removing all legacy vendor references.

8. Blueprints, Automated Audits & Mandatory Verification

Copy-Paste Blueprints

Verification Checklist Before Finishing Any Task

  1. Run all automated audits:
    node ./skills/laravel-clean-pattern/scripts/audit-controllers.cjs app/Http/Controllers
    node ./skills/laravel-clean-pattern/scripts/audit-responses.cjs .
    node ./skills/laravel-clean-pattern/scripts/audit-translations.cjs . en,ar
    
  2. Lint modified PHP files (php -l <file>).
  3. Run PHPUnit feature & unit suites (php artisan test), including DB::enableQueryLog() O(1) query assertions for N+1-sensitive endpoints.
  4. If routes/api.php was created or modified, update postman/<project-slug>.postman_collection.json and validate JSON syntax.