Skip to content
Advertisement

Prevent symfony serializer to certain attributes

I acknowledge of the existence of $normalizer->setIgnoredAttributes but I have the following problem.

I have an entity Product with attributes ‘prices’ (related with another entity) and ‘complements’ (which is a self reference relation). When I get the a product I need the prices, but when listing the complements, I don’t need the prices in the complement product, is there any way to avoid getting the attribute prices only in the complements? Something like

$normalizer->setIgnoredAttributes(array('complement->prices'));

Advertisement

Answer

There are several ways to accomplish this:

  1. Use the Serializer annotations and specify different Serialization groups
  2. Use the CustomNormalizer and make your Product implement the NormalizableInterface
  3. Write a custom normalizer class which only supports you Product entity.

The Serialization groups

By using annotations on each property of the Product entity you can specify if that property should be serialized or not, if it needs to be aliased or not, or if it belongs to one or more groups.

When serializing you can then specify via the $context array which serialization group you want to serialize and the serializer will only serialize members of that group.

The NormalizableInterface

By implementing NormalizableInterface in your Product entity you are passing the responsibility of normalization onto the entity itself. It decides what the final normalized product will look like.

By passing some information/flags in the $context array you ensure the normalization logic of the product entity will be aware if it’s currently normalizing a standard product or a complement.

The custom normalizer class

Without having to implement the NormalizableInterface on the entity your new normalizer class will only accept normalizing your Product entity (or whatever you decide to specify in supportsNormalization).

The same $context logic must apply here as with the previous example.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement