Callback on serializer Symfony

前端 未结 4 1644
借酒劲吻你
借酒劲吻你 2020-12-21 16:45

I\'m running Symfony 2.7 and I\'m trying output an object (Doctrine entity) as JSON.

When I\'m normalizing the object I want to convert some of it\'s values. To do t

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 17:00

    You can use callback normalizer of K. Dunglas component.

    You can see that in ObjectNormalizer (in normalize method)

    if (isset($this->callbacks[$attribute])) {
        $attributeValue = call_user_func($this->callbacks[$attribute], $attributeValue);
     }
    

    This mean that you must use in callback array key the name of property you wan't to normalize.

    For example in my entity I have field named "name" of type "pgarray" (like array for postgresql). I wan't to normalize this data. Instead array I want a string.

    /**
         * $object represent the property "name" because callback is attached to name property (setCallback)
         */
        $nameCallback = function ($object, $outerObject = null) {
            return $object[0];      
        };
        $this->normalizer->setCallbacks(['name' => $dateCallback]);
    

    Just remember since Symfony 4.2 you must use $context in DI to use callback.

提交回复
热议问题