core icon indicating copy to clipboard operation
core copied to clipboard

fix: prevents recomputing normalizationcontext

Open maxhelias opened this issue 1 year ago • 2 comments

Q A
Branch? 3.4
Tickets #6693
License MIT
Doc PR -

Add a check and use the previously computed context

maxhelias avatar Oct 07 '24 12:10 maxhelias

I thought about this a little bit more and I think that we shouldn't cache the context. A few things may change the context between providers and we can't be sure that the previously cached value is correct. If we do cache, every one that changes the context inside its provider needs to make sure that the _api_normalization_context is fresh... We're not even using the _api_normalization_context in our code (in DocumentationAction I don't think its useful).

soyuka avatar Oct 14 '24 08:10 soyuka

I understand. What is the recommendation in my case ? I have a database query to add a key to the context to activate some normalizer. The result of the query doesn't change during runtime. I can clearly do with 1 query.

  • Should i use a locale cache to solve it ? Maybe a mention in the documentation can be added ?
  • Or introduce a new concept/interface or something else to determine whether the result of a context builder can be cached ?

maxhelias avatar Oct 18 '24 16:10 maxhelias

sorry for the late answer I missed the comment, as the ContextBuilder is tight to Request I recommend that you do something like this:

// in a middleware, or a Provider decorating one of our system providers (https://api-platform.com/docs/core/extending/#system-providers-and-processors):

$request->attributes->set('my_queried_value', $computed');

Then create a SerializerContextBuilder that does:

return ['my_context' => $request->attributes->get('my_queried_value')] + $this->decorated->createFromRequest(...)];

soyuka avatar Oct 24 '24 13:10 soyuka

Hi @soyuka, Sorry for the late reply, I just came back to work on it and it's working well. Thanks

maxhelias avatar Nov 09 '24 15:11 maxhelias