Custom providers, query extensions & the in-memory provider¶
The Doctrine reference data layer (doctrine.md) is a fallback, not
a requirement: it registers at tag priority -128 and answers for every
entity-mapped type. Whenever you need something Doctrine can't give you — a store
that isn't Doctrine, a base query constraint the client must not be able to undo, a
type whose data isn't in any database, or a polymorphic to-many no single query can
express — you implement the SPI yourself and let autoconfiguration slot it in
ahead of the fallback.
This page is the how-to. It owns three things: the override recipe, the
DoctrineExtensionInterface query-scoping seam, and the in-memory provider as a
worked, reusable example. The SPI contracts themselves — the method signatures, the
resolution mechanics, CollectionCriteria/CriteriaApplier — live on
data-layer.md; this page references them rather than restating them.
The override recipe¶
To take over a type, implement
DataProviderInterface (and/or
DataPersisterInterface), return
true from supports() for that type, and let autoconfiguration tag the service.
services:
_defaults:
autowire: true
autoconfigure: true
haddowg\JsonApiBundle\Examples\MusicCatalog\:
resource: '../src/'
# …
That's the whole wiring. Autoconfiguration tags any DataProviderInterface with
haddowg.json_api.data_provider (JsonApiBundle::DATA_PROVIDER_TAG) and any
DataPersisterInterface with haddowg.json_api.data_persister
(DATA_PERSISTER_TAG) at the default priority 0. The bundled Doctrine
provider/persister register at -128, so the registry — which returns the first
provider whose supports() is true, in descending tag priority — picks yours for
the types it answers and falls through to Doctrine for the rest. No priority
configuration, no decorates:, no config key. (Resolution is owned by
data-layer.md.)
A custom provider should reuse the shared
CriteriaApplier so it stays
spec-conformant — it folds declared filter defaults, throws the right 400s for an
unrecognised filter[…]/sort key, and handles the - descending prefix. You only
own execution (how a filter becomes a WHERE, how a window becomes a slice).
If you keep the reference Doctrine provider and only need it to understand a new
custom FilterInterface/SortInterface, you don't need a custom provider at all —
register an arm through the
arm seam
(DoctrineFilterArmInterface/DoctrineSortArmInterface), an autoconfigured tagged
service the Doctrine handler dispatches to before it falls back to
UnsupportedFilter.
Overriding one type while keeping Doctrine for the rest¶
In the example app, OverridingArtistProvider
takes over artists and delegates everything it doesn't special-case back to the
injected Doctrine provider, so the real /artists endpoint stays intact:
final class OverridingArtistProvider implements DataProviderInterface
{
public const string SENTINEL_ID = 'override';
public function __construct(private readonly DoctrineDataProvider $doctrine) {}
public function supports(string $type): bool
{
return $type === 'artists';
}
public function fetchOne(string $type, string $id): ?object
{
if ($id === self::SENTINEL_ID) {
return new Artist(id: self::SENTINEL_ID, name: self::NAME, slug: self::SENTINEL_ID, trackCount: 0);
}
return $this->doctrine->fetchOne($type, $id);
}
// fetchCollection / fetchRelatedCollection delegate straight to $this->doctrine …
}
The Doctrine provider is still registered (the ArtistResource maps an entity); the
override wins by priority, not by the fallback being absent. Injecting
DoctrineDataProvider directly is the idiomatic way to build a thin overlay on top
of the reference path. CustomProviderTest
asserts the registry resolves OverridingArtistProvider for artists while
DoctrineDataProvider is still in the container, and that reading the sentinel id —
which no seeded row carries — returns a 200 attributable to the override alone.
Reference / static-data providers¶
The simplest custom provider serves a type whose data is not in any database — a
fixed list, a dataset from a library, or a backed enum's cases. Pair a tiny
DataProvider with a standalone #[AsJsonApiSerializer] (the serializer owns the
wire shape — see custom-serializers-hydrators.md)
and you have a read-only type with no entity, no hydrator, no persister.
Such a provider serves no relationships, so it extends
AbstractDataProvider and implements
only the three read methods (supports / fetchOne / fetchCollection) — the base
class supplies the neutral defaults for the six relationship / batch / pivot seams
(see data-layer.md), so there
are no methods to hand-stub.
The example app's countries type does exactly this.
CountryProvider
sources its rows from symfony/intl's Countries (id = ISO 3166-1 alpha-2 code,
attribute = the localized name) and the standalone
CountrySerializer
renders them, opened to just the two GET operations:
#[AsJsonApiSerializer(type: 'countries', operations: [Operation::FetchCollection, Operation::FetchOne])]
final class CountrySerializer extends AbstractSerializer implements UriTypeAwareInterface
{
// getType()/getId()/getAttributes() over the Country model …
}
A non-database source is a first-class collection, not a special case: it still
serves filter / sort / pagination. There is one wrinkle. The handler normally
sources its filter/sort vocabulary from the type's AbstractResource, but a
resource-less type declares no field inventory, so on that null-resource path (see
data-layer.md) the
handler has none to hand the provider. The provider therefore declares its own
vocabulary and rebuilds the criteria around it, then runs the shared
CriteriaApplier exactly as Doctrine and the in-memory provider do:
public function fetchCollection(string $type, CollectionCriteria $criteria): CollectionResult
{
$vocabularyCriteria = new CollectionCriteria(
$criteria->queryParameters,
[Where::make('name', 'name', 'like')],
[SortByField::make('name', 'name')],
$criteria->window,
);
/** @var list<object> $items */
$items = $this->applier->apply($vocabularyCriteria, $this->all(), $this->filterHandler, $this->sortHandler);
return $this->window($items, $criteria->queryParameters);
}
Pagination is likewise driven from the request's page[number]/page[size] and
executed as an OffsetWindow array_slice, since a resource-less type has no
server-default paginator. Where/SortByField are core's filter/sort VOs (see core
filters.md and
sorts.md); the
in-memory filter/sort handlers the applier delegates to are core's
ArrayFilterHandler/ArraySortHandler.
ReferenceDataTest
proves the whole ICU country list renders with no database behind it, that
filter[name]=United King resolves to GB via the applier, that sort=name /
-name reverse, that page[size]=2 slices into disjoint pages, that an undeclared
filter key 400s, and that only the two GET routes are emitted.
For the truly fixed case there's an even simpler variant: a backed enum. Each
case is a row, its value is the id, and a four-line fetchOne/fetchCollection over
SomeEnum::cases() paired with a serializer exposes it read-only — no model class
needed at all.
DoctrineExtensionInterface — scoping the Doctrine queries¶
When you want to keep the Doctrine reference path but constrain every query it
builds for a type — a soft-delete exclusion, tenant scoping, a published-only view,
or an eager-load join — implement
DoctrineExtensionInterface
rather than replacing the provider:
interface DoctrineExtensionInterface
{
public function supports(string $type): bool;
public function apply(QueryBuilder $builder, ExtensionContext $context): QueryBuilder;
}
Autoconfiguration tags it haddowg.json_api.doctrine_extension
(JsonApiBundle::DOCTRINE_EXTENSION_TAG). Every extension whose supports() matches
runs in descending tag priority, before the requested criteria are applied. That
ordering is the whole point:
- a client
filter[…]/sortalways composes on top of (ANDonto) your scope — it can never re-widen it; - the pre-window
COUNTof a paginated fetch is taken from the scoped builder, so totals agree with what's visible; - a single fetch whose row your scope excludes yields
null→ a JSON:API404, soGET /{type}/{id}is scoped exactly like the collection.
The example app's PublishedAlbumsExtension
scopes every albums query to published = true:
final class PublishedAlbumsExtension implements DoctrineExtensionInterface
{
public function supports(string $type): bool
{
return $type === 'albums';
}
public function apply(QueryBuilder $builder, ExtensionContext $context): QueryBuilder
{
$alias = $builder->getRootAliases()[0]
?? throw new \LogicException('The builder arrived without a root alias.');
return $builder
->andWhere(\sprintf('%s.published = :published_only', $alias))
->setParameter('published_only', true);
}
}
DoctrineExtensionTest
seeds three albums (two published, one not) and asserts the unpublished one never
appears in /albums, that filter[tracks]=1 ANDs onto the scope rather than
re-widening it, and that GET /albums/3 is a 404 while the row still exists in
the database — proof the same extension pipeline runs for the single fetch.
The ExtensionContext¶
apply() receives an
ExtensionContext carrying
everything the bundle knows about the query being built:
final readonly class ExtensionContext
{
public function __construct(
public string $type, // the resource type being scoped
public QueryPurpose $purpose, // why the query is built
public ?JsonApiRequestInterface $request = null, // the parsed request, or null
public ?ActionDescriptor $action = null, // the custom action, for ActionCollection only
) {}
public function uniqueAlias(string $name): string; // a DQL alias unique within the statement
}
$request is the seam for request-aware scoping — read a query parameter or
header off the JSON:API request and branch on it. It is populated on the
related/include/batch loads (each of which carries the request on its SPI
signature) and is null on the primary FetchOne/FetchCollection loads (whose
SPI carries no request). Branch on it only to add a constraint, falling through to
your unconditional base scope when it is absent, so the primary fetch stays scoped.
$action is set only for QueryPurpose::ActionCollection: the
ActionDescriptor of the collection action whose
filtered rows are being read. That query carries the request too.
Aliases: uniqueAlias()¶
An extension can run several times inside one DQL statement. It runs on the type
queried, and again in the subquery that keeps each relation a filter, sort or
relatedQuery reaches through to the rows your scope admits. A statement listing shelves
filtered by their books' titles applies a books extension once inside that subquery, and
a shelves extension once on the root and again wherever a hop reaches shelves.
So an extension never names an alias it adds itself. A join, or a subselect inside a
condition, takes its alias from $context->uniqueAlias('name'), which returns name
with a numeric suffix (name_1, then name_2) no other call in the same statement got:
public function apply(QueryBuilder $builder, ExtensionContext $context): QueryBuilder
{
$root = $builder->getRootAliases()[0];
$hidden = $context->uniqueAlias('hidden');
return $builder->andWhere(\sprintf(
'NOT EXISTS (SELECT %1$s.id FROM App\Entity\HiddenRow %1$s WHERE %1$s.album = %2$s)',
$hidden,
$root,
));
}
The root alias comes from getRootAliases(), as before; the bundle names it. A fixed
alias works only while the extension runs once in the statement. The second time,
Doctrine refuses the query because the alias is already defined, and the bundle answers
500 with a LogicException naming the extensions applied in the request and pointing
at uniqueAlias(). A parameter an extension binds is shared across those runs under its
name, so bind one value per name and don't reuse a name for a different value.
The QueryPurpose fail-closed contract¶
$context->purpose (QueryPurpose)
tells you why the query is being built — FetchCollection (the primary
GET /{type} collection), FetchOne (GET /{type}/{id}), or
FetchRelatedCollection (any related/include/batch load of the type while serving
another type's request, so a request-aware scope can tell a primary collection from a
related load of the same type), or IncludeHydration (the id load of a to-many include
whose ids were already scoped, see
shaping the include hydration query), or
ActionCollection (the rows a collection action reads through its type's filters, see
taking the type's filters). It is
non-exhaustive by design: the write phase
fetches an update's or delete's target through the same extension pipeline, so a
scoping rule holds for writes without re-declaration — but that means new purposes can
appear.
So apply your constraint unconditionally and branch on a purpose only to exempt
one you have a specific reason to treat differently. An exhaustive match over the
purpose would silently stop applying your tenancy or soft-delete scope the moment a
new purpose is added — scoping must fail closed. PublishedAlbumsExtension
ignores the purpose entirely, which is the common case.
Shaping the include hydration query¶
A to-many include whose rows can belong to more than one parent, such as a
many-to-many or an owning-side to-many, loads in two queries. The first selects the
(parent, related) id pairs and runs your extensions as FetchRelatedCollection, so
your scope picks the ids. The second loads the related entities by those ids with
WHERE id IN (…) and runs your extensions again as IncludeHydration.
The ids reaching that second query are already scoped. A filtering extension can
ignore the purpose and apply again, which changes nothing, or exempt
IncludeHydration to save the duplicate predicate. A query-shaping extension can opt
in to it: a fetch-join of an association the included rows render loads that
association in the same query instead of one lazy load per distinct target.
public function apply(QueryBuilder $builder, ExtensionContext $context): QueryBuilder
{
if ($context->purpose !== QueryPurpose::IncludeHydration) {
return $builder;
}
$alias = $builder->getRootAliases()[0];
return $builder->leftJoin("{$alias}.genre", 'genre')->addSelect('genre');
}
Opt in to IncludeHydration only for a join like this. The pair query's scope runs on
a subquery that selects a single id column, so a fetch-join added under
FetchRelatedCollection breaks it. A to-one include loads its targets in one id query
that is also its scope, so it reports FetchRelatedCollection, not IncludeHydration.
Two practical contracts when you write apply():
- Bound parameters are yours to name. Any name not prefixed
jsonapi_is safe — the bundle's own handlers generate theirs under that reserved prefix, so a collision is impossible.PublishedAlbumsExtensionuses:published_only. - The builder arrives ready. The root entity is selected (the alias is readable
via
$builder->getRootAliases()[0]) and, forQueryPurpose::FetchOne, the identifier constraint is already bound.
Eager-loading ?include is automatic (no extension, no extra dependency)¶
You do not need a DoctrineExtensionInterface eager-load join to avoid N+1ing
the ?include tree, and there is no library to install — include batching is
built into the bundle (it used to require an external preloader; that dependency is
gone). The bundle batch-loads a read's effective include tree automatically — one
query per relation per level, reusing core's include decision so it loads exactly
what is rendered (requested ?include or a resource's
getDefaultIncludedRelationships() fallback when none is sent). It degrades to a
lazy load for a relation it cannot batch only when reading it off the model returns
what the related endpoint would; a scoped relation it cannot load is refused.
See Eager-loading includes on the
Doctrine page.
Reach for an extension's eager-load join only for a relation you always want loaded
regardless of ?include (a join the serializer or your own code needs on every
read), or to optimise a specific access shape the per-level batch does not cover.
A custom provider participates in the same automatic batching by implementing
fetchRelatedCollectionBatch() — the provider-agnostic
RelatedIncludeBatcher orchestrates the include tree level by level and calls that
seam per included relation over the level's parents. It also calls it for a to-many
that renders linkage data without an include, over the parents whose collection
the server's relationship load state reports unloaded. A paginated to-many is asked for
its first page: the
criteria carry the paginator's window, and the result's total or hasMore drives the
page's links. Answer RelatedBatch::unsupported() and that page is read one parent at a
time through fetchRelatedCollection(), as the related endpoint reads it. With no load state wired every
relation counts as loaded, so a store whose models hold their relations in memory is
read off the model as before. Return
RelatedBatch::unsupported() for a relation you cannot batch, and
RelatedBatch::computed() for one whose value the model computes itself. An empty
new RelatedBatch([]) means every parent has no members.
Batching a relation into a type you serve¶
The same method is also called on the provider of a relation's related type, when
that provider scopes its related reads and isn't the parent type's provider. The
parents are then of another type: $parentType names it, and you key each result by
the parent's wire id, the id the parent's serializer renders. One call answers the
whole page at every level, for ?include, for linkage data, for the relationship
queries window and for ?withCount, so a grouped query over the page replaces a
fetchRelatedCollection() per parent.
public function fetchRelatedCollectionBatch(string $parentType, array $parents, RelationInterface $relation, CollectionCriteria $criteria, JsonApiRequestInterface $request): RelatedBatch
{
$runIds = \array_map(static fn(Run $run): int => $run->id, $parents);
$results = [];
foreach ($this->progress->forRuns($runIds) as $progress) { // one GROUP BY
$results[(string) $progress->runId] = new CollectionResult([$progress]);
}
return new RelatedBatch($results);
}
For a to-one, the batch is where the target comes from: the first item for a parent
is its target, and no item means null. The parent model needs no property, getter or
extractUsing() for it. The bundle reads the target from your batch on every path that
renders it: an include, linkage, the related and relationship endpoints, and a
relatedQuery or ?filter check, where your relatedToOneMatches() then runs
against the target you returned. A single parent is a one-element batch, and the
batch for a page is read once per request and shared by those paths. A to-one is asked
with empty criteria; a to-many gets the criteria its per-parent fetch would, window
and default order included. A ?withCount asks with the count's filters and no window,
and counts each parent's total when you set one, else its items.
Answer RelatedBatch::unsupported(), the AbstractDataProvider default, and the
bundle keeps reading the relation one parent at a time, through
fetchRelatedCollection() for a to-many and the parent's value plus
relatedToOneMatches() for a to-one. RelatedBatch::computed() is read the same
way, since the related type's scope still applies to what the model holds. A pivot
belongsToMany is always read per parent through its pivot query, and a polymorphic
relation is never batched this way.
Reading a relation through a foreign key¶
A relation declared with a foreign key
(relationships → relations read through a foreign key)
is read by its related type's provider through
ReadsByForeignKeyInterface, on
every path and whatever provider serves the parents. Implement it on a provider whose
type is the target of such a relation; warm-up refuses one that doesn't.
public function fetchByForeignKey(string $relatedType, RelationInterface $relation, ForeignKey $foreignKey, ForeignKeyParents $parents, CollectionCriteria $criteria, JsonApiRequestInterface $request): RelatedBatch
{
// $foreignKey->column is the member's storage name; $parents->keys maps each
// parent's wire id to the key the column holds.
$rows = $this->notes->whereIn($foreignKey->column, \array_values($parents->keys)); // one query
// ...partition the rows by $parents->wireIdOf($row->{$foreignKey->column}), then cut
// each partition to $criteria's window as fetchRelatedCollection() would.
}
countByForeignKey() counts each parent's rows over the criteria's filters, 0 for a
parent with none. A to-one's page holds its target as the first row. When the foreign
key is a to-one relation ($foreignKey->isRelation()), the column holds a reference to
the parent, so compare the id it references. The parents may come from any provider, so
read their keys from ForeignKeyParents rather than from your own storage.
When the foreign key is a MorphTo, as a MorphMany or MorphOne names it,
$foreignKey->morphColumns() returns its two fields: keep the type field to
morphColumns()->storedValues($parents->type) as well as the id field to the parents'
keys, or rows pointing at another type with the same id are read too. The id field may
hold a parent's storage key or its wire id, so match both, as StoredIdForms::forms()
lists them with $parents->encoder, and $parents->wireIdOf() maps a stored value back
to its parent in any of those forms.
A provider that can only scope its related reads to parents of some types implements
ScopesToParentsInterface. The Doctrine
provider answers true only for the types its entities map, and for any other parent
type a to-many with no foreign key reads what the parent model holds, its pages cut in
memory.
Saying whether related reads are scoped¶
Included and linkage data always match the related endpoint (see
relationships → included data is scoped like the related endpoint).
To know when it may read a relation straight off the parent, the bundle asks the
provider of each of the relation's related types (a polymorphic relation is scoped when
any of them is) through
ScopesRelatedReadsInterface:
final class TenantAgencyProvider implements DataProviderInterface, ScopesRelatedReadsInterface
{
public function scopesRelatedReads(RelationInterface $relation): bool
{
return true; // fetchRelatedCollection() filters by tenant
}
// ...
}
Return false only when your related reads return exactly what the parent model
holds. A relation declared with a foreign key always reads through the related type's
provider, whatever it answers. A to-many with a
default read order loads through
your fetchRelatedCollectionBatch() whatever you answer, with the order in the
criteria's defaultSort, since the model's own order isn't the one its endpoints
serve. A provider that does not implement the interface is treated as scoping every
relation: its relations are loaded through it, in one batch or per parent when the
parent type has a different provider
(see batching a relation into a type you serve),
and one it cannot load (an unsupported() batch) is refused with a 500. A polymorphic relation's members are kept per member type: the rows of a type
your provider scopes render only when your admitRows() (from AdmitsRowsInterface)
or your fetchOne() returns them. AbstractDataProvider implements it
and returns false, so override it there when your reads filter.
Writes check linkage through your provider whatever it answers: before any persister
runs, each id a write names must come back from your fetchByIds() or admitIds() when
you implement either, or from fetchOne(), and one that doesn't is a 404
(see relationships → written linkage).
Make those reads apply the same scope as your related reads.
Reading pivot rows¶
A belongsToMany with stored pivot fields renders each member's meta.pivot wherever its
linkage data renders, and the provider of its related type reads the stored values. Implement
PivotAwareProviderInterface on it: fetchRelatedPivotMap() returns one parent's values and
fetchRelatedPivotMapBatch() every parent's at one include path, keyed by the parent's wire id
and then the member's. Both take the served parent type first, $parentType, $relatedType,
so a provider serving one object as several types can tell them apart. supportsPivot() says whether it also queries the rows, filtering,
sorting and paging a related read by a pivot field through fetchRelatedPivotCollection();
answer false and the related reads take the plain path, as the in-memory provider's do. A
related read that returns a PivotCollectionResult, from fetchRelatedPivotCollection() or
from fetchRelatedCollectionBatch() for an include, carries its members' values, so they
render from that page, and fetchRelatedPivotMapBatch() is asked only for the parents whose
page didn't carry them. A relation with stored pivot fields whose related type's provider
doesn't implement the interface fails the cache warm-up, naming the relation, the type, the
provider and the interface.
Loading many rows by id¶
A MorphTo declared with identifiedBy() stores its target as a type and id pair, so
an include or its related endpoint loads the targets by id
(see relationships → a MorphTo stored as a type and id pair).
The bundle asks each target type's provider once, through
FetchesByIdsInterface:
public function fetchByIds(string $type, array $ids, JsonApiRequestInterface $request): array
{
return $this->agencies->findVisibleByIds($ids); // one WHERE id IN (...)
}
public function scopesFetchByIds(string $type): bool
{
return true; // findVisibleByIds() hides archived agencies
}
The ids are wire ids, as fetchOne() takes them. Return the rows your scope admits, in
any order, and leave out the ids no row holds. The interface also has
scopesFetchByIds(string $type): return true when your scope can hide a row of the
type. A pair naming such a type loads its target even when the relation is only linked,
so the scope decides, while a pair naming a type you never hide renders without a load.
The answer is cached per server and type. A provider that doesn't implement the
interface is asked through fetchOne(), one id at a time, and counts as scoping unless
its scopesRelatedReads() says otherwise. The Doctrine and in-memory providers implement
it; the Doctrine one runs one WHERE id IN (...) with the type's extensions under
QueryPurpose::FetchRelatedCollection, and scopes a type when an extension supports it.
A MorphToMany declared with identifiedBy() also has to know which of a parent's
stored ids a scope admits before it cuts a page or takes a count, without loading every
row. A provider that can answer that from ids alone implements
AdmitsIdsInterface:
public function admitIds(string $type, array $ids, JsonApiRequestInterface $request): array
{
return $this->agencies->visibleIdsAmong($ids); // SELECT id ... WHERE id IN (...)
}
Return the wire ids your scope admits, in any order. Without it the bundle loads the
rows through fetchByIds() and keeps their ids, or asks fetchOne() one id at a time.
The Doctrine provider runs one id-only WHERE id IN (...) under the type's extensions,
and the in-memory provider checks its store.
The in-memory provider as a worked example¶
InMemoryDataProvider,
InMemoryDataPersister and
InMemoryStore live in src/ (not
tests/) precisely so they're a documented, reusable example — mirroring how core
ships its InMemory\Array{Filter,Sort}Handler. They're the in-memory analogue of a
real adapter's read half + write half + the database both talk to, and they're the
fastest way to stand a type up without a schema.
One instance answers for a single $type. The provider construction is:
new InMemoryDataProvider(
string $type,
iterable $items, // objects keyed by id
?\Closure $identify = null, // reads an item's id; required ONLY for writes
?\Closure $assignId = null, // writes a minted id onto an item (store-provided/auto-increment ids on create)
string $idColumn = 'id', // the member the cursor (keyset) page reads as the PK tiebreaker
iterable $filterArms = [], // ArrayFilterArmInterface arms for custom filters
iterable $sortArms = [], // ArraySortArmInterface arms for custom sorts
?InMemorySnapshotCoordinator $coordinator = null, // shared across stores for atomic rollback
);
Reads need only the seed map; the $identify closure is consulted only when a
persister writes through the store, and $assignId/$idColumn are write-path /
keyset concerns — $assignId lets the shared store mint a store-provided
(auto-increment) id on an id-less create, and $idColumn names the model member the
cursor (keyset) page reads as its primary-key tiebreaker (defaults to id). This
provider is built by hand rather than from the container, so arms for custom filter
and sort value objects go in $filterArms and $sortArms instead of being tagged.
Pass the same $coordinator to every store that takes part in an atomic batch, so a
rollback restores them together and keeps object identity across them. Pair it
with a persister over the same store (via $provider->store()) so a create is
immediately readable:
new InMemoryDataPersister(
string $type,
InMemoryStore $store, // the read provider's store()
\Closure $factory, // builds the blank create instance
?\Closure $relatedResolver = null, // (type, id) → ?object, for relationship mutation
);
The example app is Doctrine end-to-end, but the bundle's own conformance kernels show the copyable factory-plus-tag wiring. A factory method builds the seeded pair:
/**
* @return InMemoryDataProvider<Article>
*/
public static function createProvider(): InMemoryDataProvider
{
// … build $articles keyed by id …
return new InMemoryDataProvider('articles', $articles, static fn(Article $item): string => $item->id);
}
/**
* @param InMemoryDataProvider<Article> $provider
*
* @return InMemoryDataPersister<Article>
*/
public static function createPersister(InMemoryDataProvider $provider): InMemoryDataPersister
{
return new InMemoryDataPersister('articles', $provider->store(), static fn(): Article => new Article());
}
The provider, its store and the persister take the class of the rows as a template
type, read from the seeded rows or from the closures, so identify and assignId can
type their item as that class and pass PHPStan. A declaration that names the classes
without the type, such as the return type InMemoryDataProvider, reads as rows of any
object, and InMemoryDataProvider<Article> names one class.
The kernel registers each as a service, hands the persister the same provider, and applies the two tags:
$services->set('test.articles_provider', InMemoryDataProvider::class)
->factory([WritableArticleFactory::class, 'createProvider'])
->tag(JsonApiBundle::DATA_PROVIDER_TAG);
// The persister shares the provider's store, so writes are readable.
$services->set('test.articles_persister', InMemoryDataPersister::class)
->factory([WritableArticleFactory::class, 'createPersister'])
->args([service('test.articles_provider')])
->tag(JsonApiBundle::DATA_PERSISTER_TAG);
A factory is needed because the seed objects can't be service-configuration argument
literals. Both tags register at the default priority 0, so this pair shadows the
Doctrine fallback for articles with no further config.
Seed relations with the related objects, not their ids: a to-one property holds the
related object (or null), a to-many holds a list of them. The in-memory store renders
relations straight off the model, so it can't look an id up. A model that holds an id
where an object belongs fails the read with a \LogicException naming the type and the
relation, rather than rendering an identifier with an empty id.
The in-memory store keeps each parent's pivot rows beside it and reads them through
PivotAwareProviderInterface, so every response renders their stored fields, but it doesn't
query them. Seed rows with
$provider->store()->writePivotRows($parent, $relationColumn, [$memberId => [$column => $value]]).
Pivot paths need a store that queries pivot rows. On a type it serves, a filter whose ->through() path starts at pivot and reads a pivot field
answers 400, as a pivot column filter does. A path with pivot after a relation, such as
tracks.playlists.pivot, answers 400 too, and so does a filter default declared on one,
on every read that applies it. A path that goes on past pivot, such as
pivot.addedBy, fails the cache warm-up, since nothing names the relations an in-memory
pivot row would hold. A relation whose default order reaches through its pivot row fails
the warm-up as well.
The $relatedResolver requirement¶
A persister with no $relatedResolver supports only whole-resource writes
(create/update/delete). The store holds related objects, not raw ids, so
mutateRelationship() needs a (type, id) → ?object closure to turn an incoming
linkage id back into the stored object before setting it on the parent — without one,
it throws. Wire it as a lookup across the related types' stores:
return new InMemoryDataPersister(
'articles',
self::articles()->store(),
static fn(): Article => new Article(),
static function (string $type, string $id) use ($authors, $comments): ?object {
return match ($type) {
'authors' => $authors->store()->find($id),
'comments' => $comments->store()->find($id),
default => null,
};
},
);
(Relationship mutation itself is owned by relationships.md; the
mutateRelationship() signature is on data-layer.md.)
The $request argument in fetchRelatedCollection¶
fetchRelatedCollection() is handed a
JsonApiRequestInterface
the Doctrine provider ignores (it pushes the scope down into a QueryBuilder) but
the in-memory provider uses — it reads the related objects straight off the parent
via the relation's public accessor:
readValue() honours a relation's storedAs/extractUsing (core
relations.md), so a
custom extractUsing extractor that consults the request gets it here. If you write a
provider that resolves related collections off the parent object, this is the argument
you thread through.
Replacing Doctrine for a polymorphic to-many¶
The reference Doctrine provider throws on a polymorphic MorphToMany related
collection — its members span entity classes, so no single scoped query can express
it (see doctrine.md and relationships.md). The
escape hatch is a custom provider that resolves the members across their per-type
repositories.
The example app's LibraryItemsProvider
does this for libraries.items (a mixed Track | Album | Artist collection). It
delegates the parent fetch to the Doctrine provider, then populates the non-mapped
Library::$items by looking each member up in the right repository — sharing the
EntityManagerInterface so every resolved row comes back managed:
private function resolveItems(string $libraryId): array
{
$entityClassByType = ['tracks' => Track::class, 'albums' => Album::class, 'artists' => Artist::class];
$items = [];
foreach (self::ITEMS_BY_LIBRARY[$libraryId] ?? [] as $pointer) {
$entityClass = $entityClassByType[$pointer['type']] ?? null;
if ($entityClass === null) {
continue;
}
$member = $this->entityManager->getRepository($entityClass)->find($pointer['id']);
if ($member !== null) {
$items[] = $member;
}
}
return $items;
}
A polymorphic to-many carries no shared filter/sort vocabulary, so the criteria here
only ever window — LibraryItemsProvider reuses CriteriaApplier (a no-op for the
absent filters/sorts) and an OffsetWindow slice, exactly like the in-memory
provider. The same shape resolves a polymorphic to-one (MorphTo): the example's
FavoriteProvider
fills a Favorite's non-mapped target from its stored targetType/targetId pair.
Next / See also¶
- data-layer.md — the SPI contracts, the resolution registry, and the
CrudOperationHandlerthese providers plug into. - doctrine.md — the reference implementation you're overriding or scoping, and the polymorphic-to-many boundary.
- custom-serializers-hydrators.md — the standalone serializer that pairs with a reference-data provider.
- relationships.md — related/relationship endpoints and the polymorphic rendering a custom provider feeds.
- Core adapters.md —
the
FilterHandlerInterface/SortHandlerInterfacesemantics and the array handlers the in-memory provider delegates to.