[英]Symfony 4. Unregister ObjectNormalizer
I want my serialization process to be explicit, without using Object/Property normalizers, how do I unregister them? 我希望我的序列化过程是明确的,而不使用对象/属性规范化器,如何注销它们?
http://symfony.com/doc/current/components/serializer.html#normalizers http://symfony.com/doc/current/components/serializer.html#normalizers
I found a way by adding compiler pass in Kernel::build
: 我通过在
Kernel::build
添加编译器传递找到了一种方法:
class Kernel extends BaseKernel
{
// ...
protected function build(ContainerBuilder $container)
{
$container->addCompilerPass(new class implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$container->removeDefinition('serializer.normalizer.json_serializable');
$container->removeDefinition('serializer.normalizer.object');
}
}, PassConfig::TYPE_BEFORE_OPTIMIZATION, 1);
}
}
Priority = 1 makes it run before SerializerPass
so it works. Priority = 1使它在
SerializerPass
之前运行,因此它可以工作。
UPD : @Nek's advice to disable serializer in framework
config and register it myself seems like a good idea. UPD :@Nek建议禁用
framework
配置中的序列化程序并自行注册,这似乎是个好主意。
If you want your serialization process to be explicit, you can register your own normalizer like follow in a services definition
如果您希望序列化过程是明确的,则可以注册自己的规范化器,例如在服务
definition
遵循
AppBundle\Serializer\Your\MyObjectNormalizer:
tags:
- { name: serializer.normalizer }
You could declare a normalizer like follow 您可以像下面这样声明一个规范化器
namespace AppBundle\Serializer\Your;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class MyObjectNormalizer implements NormalizerInterface
{
public function normalize($object, $format = null, array $context = [])
{
// $object is an instance of MyObject
$groups = array_key_exists('groups', $context) ? $context['groups'] : [];
$data = [
'name' => $object->getName()
// ..........
];
if(array_key_exists('full', $groups)) {
$data['owner'] = $object->getOwner()->getFullName();
}
return $data;
}
/**
* Checks whether the given class is supported for normalization by this normalizer.
*
* @param mixed $data Data to normalize
* @param string $format The format being (de-)serialized from or into
*
* @return bool
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof MyObject;
}
}
If you process like follow Symfony will see that you declared a custom normalizer for this kind of object. 如果您按照如下方式进行处理,Symfony将看到您已声明了针对此类对象的自定义规范化器。 So he'll take your class in first priority to normalize
MyObject
因此,他将把您的课程放在第一位来规范
MyObject
You can normalize data from the context array 您可以标准化上下文数组中的数据
$myobject = new MyObject();
$fullObj = $this->container->get('serializer')->serialize($myobject, 'json', ['full']);
$lightObj = $this->container->get('serializer')->serialize($myobject, 'json');
// $fullObj is ['name' => 'someName', 'owner' => 'ownerName'];
// $lightObj is ['name' => 'someName'];
Take a look at this part of the documentation 看看文档的这一部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.