简体   繁体   中英

How can I remove deprecated message for circular reference handler (Symfony 4)?

I am trying to remove this error message:

User Deprecated: The "Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer::setCircularReferenceHandler()" method is deprecated since Symfony 4.2, use the "circular_reference_handler" key of the context instead.

Here is my code:

 $encoder = new JsonEncoder();
    $normalizer = new ObjectNormalizer();
    $normalizer->setCircularReferenceHandler(function ($object, string $format = null, array $context = []) {
        return $object->getName();
    });

I made a composer update and cache clear. But nothing helps.

The error message tells that you should give it in the defaultContext array you can give that as third parameter in the costructor.

public function __construct(ClassMetadataFactoryInterface 
$classMetadataFactory = null, NameConverterInterface $nameConverter = null, array $defaultContext = array())

in your case it would be:

$encoders = array(new JsonEncoder());
$normalizer = new JsonSerializableNormalizer(null,null,array(JsonSerializableNormalizer::CIRCULAR_REFERENCE_HANDLER=>function ($object) {
    return (string)$object;
}));

EDIT:
I was using a JsonSerializableNormalizer and you an ObjectNormalizer then the constructor definition is:

public function __construct(ClassMetadataFactoryInterface $classMetadataFactory = null, NameConverterInterface $nameConverter = null, PropertyAccessorInterface $propertyAccessor = null, PropertyTypeExtractorInterface $propertyTypeExtractor = null, ClassDiscriminatorResolverInterface $classDiscriminatorResolver = null, callable $objectClassResolver = null, array $defaultContext = array())

and used in your program it should be:

$normalizer = new ObjectNormalizer(null,null,null,null,null,null,array(ObjectNormalizer::CIRCULAR_REFERENCE_HANDLER=>function ($object) {
    return (string)$object;
}));

you should use it ( circular_reference_handler ) as configuration key. For example,

serializer:
    circular_reference_handler: App\Service\YourHandlerService

I tried it in framework.yaml and it works.

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