api-platform / core

The server component of API Platform: hypermedia and GraphQL APIs in minutes
https://api-platform.com
MIT License
2.45k stars 874 forks source link

[Laravel] Feature: Support custom Normalizers #6677

Closed toitzi closed 1 month ago

toitzi commented 1 month ago

Description
In Laravel applications, it's common to cast model attributes using casts. For example, you can cast a value as an Enum or any custom class that supports casting:

image

The issue is that API Platform currently only handles casted types if they are compatible with one of the normalizers registered by the package:

image

otherwise this will throw an Error. While it may work fine for many cases, casting to other types — such as enums — is quite common in Laravel. If API Platform would support custom Normalizers, one could just write his own EnumNormalizer and still profit from Laravel Casts.

Example

In config/api-platform.php

'normalizer' => [
    \App\Normalizer\EnumNormalizer::class => -920, // Class => Priority
],

Possible implementation Create the config entry, insert the normalizers inside the ApiPlatformProvider. Pretty straight forward tbh.

Workarround

Since this package heavily utilizes Laravel’s container classes, it’s possible to achieve this behavior by adding a custom service provider in Laravel and overriding the shared container binding.

Summary I believe supporting this out of the box would be valuable, as it's a common practice. However, since there is a clean workaround available, it’s ultimately up to you whether to implement it. If you're interested, I’ve already patched this and can happily create a PR and update the documentation.

dunglas commented 1 month ago

Hi,

Indeed the recommended way to handle this is to use Laravel DI. Maybe adding some documentation explaining how to do that would be enough?

If it's not, we could maybe add add a specific config option, a new attribute or a trait to register a new normalizer in a more easy way?

toitzi commented 1 month ago

You are probably right. Not doing it now, does not mean it cannot be done later if it is needed by more people / or makes more sense at some point later on.

I will close this and do a Docs PR! :)