简体   繁体   中英

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'));

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.

Should you ever need to completely exclude a property from being serialized, then since Symfony version 5.1 you have a much simpler option: the @Ignore annotation:

For example:

use Symfony\Component\Serializer\Annotation\Ignore;

class User
{
    public $login;
    public $email;

    /**
     * @Ignore
     */
    public $password;
}

And it works on access methods too:

class User
{
    // ...
    
    /**
     * @Ignore
     */
    public function getPassword(): string {}

    /**
     * @Ignore
     */
    public function isAdmin(): bool {}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM