Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add global handlers for all data types #1587

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

MoviU
Copy link

@MoviU MoviU commented Feb 20, 2025

Q A
Bug fix? no
New feature? yes
Doc updated yes
BC breaks? no
Deprecations? no
Tests pass? yes
License MIT

Allow custom handlers for all types. ("type" => "*").

@scyzoryck
Copy link
Collaborator

Hello.
What would be a usage case for it?

Best, Marcin.

@MoviU
Copy link
Author

MoviU commented Feb 20, 2025

Hi,

In some cases, the default serialization behavior needs to be customized. For example, in my current use case, if a DTO is marked with a specific attribute (e.g., #[CustomDTO]), I need to apply custom serialization logic—such as inspecting property attributes and executing specific logic when a custom attribute is found.

My current implementation maps a handler to every DTO within a given namespace. This approach relies heavily on Composer’s autoloading and requires cache revalidation whenever changes occur in that namespace (e.g., when a new DTO is created).

Allowing handlers to apply to all types would enable seamless customization of the default serialization process without the need for complex workarounds.

@scyzoryck
Copy link
Collaborator

I think adding custom Handler for all classes will create multiple issues - for example with depth exclusions that might not work as expected.
May event system may solve your issues? https://github.com/schmittjoh/serializer/blob/033c9beab9eb708509a3d400e9f0ffeb2d440e71/doc/event_system.rst#serializerpre_serialize
You can change the type to * for any class that needs to handled by your custom Handler.

@MoviU
Copy link
Author

MoviU commented Feb 20, 2025

The issue I encountered with events during deserialization is that they operate on an already deserialized instance.

If the DTO is readonly, modifying its properties directly isn't possible. Instead, I would need to create a new instance with the updated data.

However, the event system doesn't allow replacing the deserialized result.

Maybe there is another way to achieve this? What do you think?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants