Repository navigation
Pass typed values through TransformationContext to transformers
#1216
EgorGruzdev
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
The problem
A transformer sometimes needs request-scoped data that is not part of the data object: the viewer's display currency, a locale, a timezone, a feature flag. The transformer instance can't hold it. Property transformers (
#[WithTransformer]) are created once per property and cached together with the data structure, so they're shared across requests and have to stay stateless.TransformationContextis the natural carrier: it's created pertransform()call and passed down to nested data objects and collections. However, it only has fixed fields (transformValues,mapPropertyNames,transformers, partials, depth, …), and there is no supported way to attach your own value.Our use case
API responses keep amounts in the order's currency. The data object stays self-contained: amounts plus the currency code, a consistent pair. Converting them to the viewer's display currency is a presentation concern, so it should happen on output and only when the caller asks for it:
Without a converter in the context, the transformers return values as they are. Logging,
toArray()and service-to-service use then get the order currency.Current workaround
We put the converter into the global transformers collection under its own class name, a key that never matches a real value:
The property transformer then gets it back by iterating, because
GlobalTransformersCollectionhas no lookup by key:It works, and nested data objects receive it because the cloned context shares the collection. But it misuses the collection as a dependency bag. The carrier also has to implement
Transformerwith atransform()that is never meant to run, and the code relies on how the collection is used internally.Proposal
Let the context carry typed values keyed by class, similar to Laravel's
Contextor a small container:TransformationContextand new methods on the factory. TheTransformersignature doesn't change, unlike feat!: add context to transformers #589, which was closed because of the breaking change.transformersalready is (shallow clone).get()can be annotated with@template T/class-string<T>→?Tfor static analysis.A smaller alternative is
GlobalTransformersCollection::get(string $transformable): ?Transformer. It would remove the iteration, but it would also endorse storing non-transformers there, so the typed values look like the cleaner option.If you think this fits (v5 might be a good moment), I'm happy to open a PR.
Prior discussions
I searched the existing discussions, issues and PRs and didn't find this exact request. The closest ones are:
Transformercontract. Closed because it was a breaking change.All reactions