persistence-patterns
Use this skill when implementing database persistence, choosing a data source pattern, managing repository interfaces, writing mappers, or splitting large repositories. Assumes the decision between a rich domain model and a lean ORM model has already been made by the php-domain-modeling skill.
How do I install this agent skill?
npx skills add https://github.com/garrettw/php-arch-skills --skill persistence-patternsIs this agent skill safe to install?
- Gen Agent Trust Hubpass
The skill provides architectural guidance for implementing persistence patterns in PHP, such as Data Mappers, Repositories, and Active Record. It contains educational documentation and code samples that follow industry best practices. No security issues were detected.
- Socketpass
No alerts
- Snykpass
Risk: LOW · No issues
What does this agent skill do?
Persistence, Mappers & Repositories in PHP
When to Use Rich Persistence vs. Simple ORM
Rich persistence (Mapper + Repository) is only worth the ceremony when the application has complex invariants that persistence concerns would otherwise compromise. Easy storage swaps are rarely the real benefit (see data-mapper.md). Use simple ORM for straightforward CRUD.
| Use Rich Persistence (Mapper + Repository) | Use Simple ORM (Entity + Query Builder) |
|---|---|
| Complex business invariants to protect | Single-table CRUD with few rules |
| Domain must stay free of persistence code | The schema is the model |
| Tests must run without DB for domain logic | Schema changes hand-in-hand with feature |
| Long-lived system, evolving requirements | Prototype, MVP, throwaway code |
A library or package that simply exposes data objects should not include mappers or repository interfaces.
Data Source Spectrum & Gateway vs Repository
Persistence structure is a separate axis from domain-logic style. There is a progression of increasing separation between business logic and storage: Table Data Gateway → Row Data Gateway → Active Record → Data Mapper. Pick the lightest one that fits the area: a Table Data Gateway for rows with no behavior, Active Record for CRUD-heavy areas with modest rules, and a Data Mapper when a rich domain model must stay free of persistence concerns. Avoid Row Data Gateway in new code. data-source-patterns.md is the full treatment of the spectrum, its philosophy, and when Active Record has outgrown its limits.
The distinction between a Gateway and a Repository is subtle but critical:
- A Gateway thinks in tables: "How do I fetch rows from this table?" It returns rows/recordsets and uses persistence language.
- A Repository thinks in business concepts: "How do I retrieve domain objects?" It returns domain objects in the ubiquitous language.
A Table Data Gateway is not a Repository, even when teams label it CustomerRepository. Modern equivalents (query services, table repositories, DAOs, SQL abstraction classes) are all gateways if they think in tables. A gateway accumulates procedural query methods (findEligiblePremiumCustomers()) as behavior grows; that is the signal you have started building a Repository without realizing it — move the behavior into the domain and let a true Repository return domain objects.
Object-Relational Patterns (ORM Features, not to Implement)
Beyond the data-source spectrum, ORMs implement a second family of Object-Relational patterns internally — behavioral (Unit of Work, Identity Map, Lazy Loading) and structural (Identity Field, Foreign Key Mapping, Association Table Mapping, Dependent Mapping, Embedded Value). Architects should understand these and their tradeoffs as ORM features, and make the architectural decision at the level of ORM selection and configuration rather than reimplementing them. See orm-patterns.md. The patterns that surround the ORM rather than live inside it — Metadata Mapping, Query Object, Repository, Value Object — are engaged with architecturally; see orm-architecture-patterns.md.
System Overview
A clear persistence strategy separates the domain model from database storage mechanisms when necessary, while avoiding boilerplate when it is not. This skill helps you decide when to use a full DDD persistence structure (Domain → Mapper → Repository → ORM) versus a lean ORM structure.
Numbered Workflows
1. Separating Read and Write Paths
If implementing persistence for a use case:
- For Writes (Commands): If the feature uses a rich domain model, use a Mapper and a Repository to load the aggregate, mutate it, and save it. This protects invariants.
- For Reads (Queries): Bypass mappers entirely. Use the ORM, Query Builder, or raw SQL to fetch data directly into lean DTOs or arrays for performance and simplicity.
- For Lean Features: If the
php-domain-modelingskill determined the feature is just CRUD, use the ORM directly for both reads and writes.
This split is not CQRS: it reads and writes the same model and store, and is fine from the start. CQRS (separate read and write models, often projections) is a later, opt-in step; see application-layer.
2. Implementing Mappers
If you must map between a rich domain object and an ORM entity:
- Isolate Mapping Logic. Create a dedicated Mapper class. Do not put mapping logic in the domain object or the repository.
- Accept the Cost. Acknowledge that adding a database column now requires updating the domain, ORM entity, mapper, and tests. Only map objects that have real business logic justifying this cost.
3. Introducing Repository Interfaces
If creating a new repository:
- Apply the interface rule in
dependency-injection(workflow 1). In a layered or hexagonal area, an Application handler depends on the repository while its implementation lives in Infrastructure. Introduce a[Name]Repositoryinterface in the Domain layer as a driven port, even with one implementation, and name the implementation after its technology (Doctrine[Name]Repository,Pdo[Name]Repository); see the naming note independency-injection, workflow 1. - In a lean area (Transaction Script, lean ORM, no ports and adapters), create only a concrete
[Name]Repository. - Per Aggregate. Design repositories per aggregate root, not per database table. A single aggregate should be loaded and saved through one repository.
4. Splitting Large Repositories
If a repository is growing too large:
- Check Heuristics. Does it implement 4+ interfaces, exceed 400 lines, or have 25+ methods?
- Analyze Return Types. Do methods return raw DTOs instead of Domain models?
- Refactor. If yes, split the repository or extract dedicated Query services.
Transaction & Flush Boundaries
The ORM's default request-end flush is not your only transaction boundary. Transaction boundaries are a business decision owned by the application layer, not the ORM. Default to one flush and one commit per use case for atomicity. A flush is not a commit: flush mid-transaction only for same-connection needs (a generated ID, a later query in the same transaction); anything outside the transaction (queued jobs, other contexts) learns about the change through the outbox after commit. See transaction-boundaries.md.
Performance & Caching
Measure query count, plans, latency, and data volume before optimizing. Prefer the simplest read shape that meets the need; introduce caching only with explicit staleness, invalidation, key-scope, and outage behavior. See performance-and-caching.md.
Recognizing Persistence Problems in an Existing Codebase
When analyzing persistence code, these are the smells to look for (signals, not automatic defects — fix only when you next touch the area):
- N+1 query load. A list endpoint issues one query per row to fetch related data, so request cost grows linearly with row count. Fix with eager joins, a batch fetch, or a projection. This is the most common performance debt in PHP backends.
- Unbounded result sets. A list endpoint returns every row with no limit/offset or cursor pagination, so response size and query time grow without bound. Always paginate collection endpoints.
- Schema drift. Production schema has diverged from the migration history, so a fresh migration does not reproduce production. Migrations must be the only source of schema change.
- Missing indexes / orphaned records. Hot query columns lack indexes (sequential scans) or foreign keys are not enforced, leaving orphaned children. Enforce referential integrity and index frequently-queried columns.
- Repository per entity. One repo per entity instead of per aggregate root, which lets callers bypass aggregate consistency boundaries.
- Gateway wearing a Repository's name. A class called
XRepositorythat returns rows and speaks persistence language is really a Table Data Gateway. Call it what it is and keep business behavior in the domain.
The Repository pattern is DRY applied to data access (one authoritative place knows how to load/save an aggregate) and an expression of Separation of Concerns; see clean-code-foundations.md.
Boundaries
Always Do
- Always consider the hybrid approach in rich areas: write through aggregates (to protect invariants) and read through lean queries (for performance and simplicity).
- Always use specific repository interfaces per bounded context rather than a single massive repository shared across contexts.
- Always distinguish a Gateway (thinks in tables, returns rows) from a Repository (thinks in business concepts, returns domain objects). A Table Data Gateway is the right tool at the lean/CRUD end of the spectrum.
Ask First
- Ask before introducing a repository interface in a lean area that does not use ports and adapters.
- Ask whether a class named "Repository" is actually a Gateway in disguise (returns rows, uses persistence language). If so, call it what it is.
- Ask whether a workflow that "needs the row to exist now" is a signal for an outbox/domain-event pattern rather than a mid-request flush.
Never Do
- Never create a massive global repository (e.g.,
UserRepository) that serves multiple bounded contexts. - Never let a Table Data Gateway accumulate business-flavored query methods (
findEligiblePremiumCustomers()); that is a Repository trying to form — move the behavior into the domain instead. - Never reach for Row Data Gateway in new code; it is a faded pattern that awkwardly mixes persistence, identity, and row state without business behavior. Use Table Data Gateway for raw row access, Active Record for row+behavior, or Data Mapper for full separation.
- Never introduce CQRS (separate read and write models or stores) before the application has divergent read/write workloads. Lean queries alongside aggregate writes do not count as CQRS and need no such justification.
- Never strictly create one repository per entity. Reaching for an entity-level repository bypasses aggregate consistency and scatters persistence logic; design one repository per aggregate root instead.
- Never add a cache without defining its staleness, invalidation, and tenant/authorization key scope.
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/garrettw/php-arch-skills/persistence-patterns">View persistence-patterns on skillZs</a>