如何在Symfony序列化程序中使用(链化)多个规范化程序?

Mar*_*rio 5 php serialization serializer symfony

有人可以用Symfony序列化器序列化来自多个类的数据时,如何解释我如何使用多个标准化器?

可以说我有以下课程:

class User
{
    private $name;
    private $books;

    public function __construct()
    {
        $this->books = new ArrayCollection();
    }

    // getters and setters
}

class Book
{
    private $title;

    public function getTitle()
    {
        return $this->title;
    }    

    public function setTitle($title)
    {
        $this->title = $title;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想序列化拥有多本书的用户。

$first = new Book();
$first->setTitle('First book');

$second = new Book();
$second->setTitle('Second book');

$user = new User();
$user->setName('Person name');
$user->addBook($first);
$user->addBook($second);

dump($this->get('serializer')->serialize($user, 'json'));
die();
Run Code Online (Sandbox Code Playgroud)

假设我还想在对书籍进行序列化时包含哈希,因此我有以下规范化器:

class BookNormalizer implements NormalizerInterface
{
    public function normalize($object, $format = null, array $context = array())
    {
        return [
            'title' => $object->getTitle(),
            'hash' => md5($object->getTitle())
        ];
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof Book;
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到了预期的结果: {"name":"Person name","books":[{"title":"First book","hash":"a9c04245e768bc5bedd57ebd62a6309e"},{"title":"Second book","hash":"c431a001cb16a82a937579a50ea12e51"}]}

当我还为User类添加规范化器时,就会出现问题:

class UserNormalizer implements NormalizerInterface
{
    public function normalize($object, $format = null, array $context = array())
    {
        return [
            'name' => $object->getName(),
            'books' => $object->getBooks()
        ];
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof User;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,这些书没有使用先前给定的规范化器进行规范化,我得到以下信息: {"name":"Person name","books":[{},{}]}

我试图找到一种方法(文档和其他文章)始终调用给定类型的规范化器(例如,即使类型为Book的数据嵌套并且在另一个规范化器中使用,也总是在类型为Book时调用book规范化器),但是无法成功。

我认为我对规范化器有误解,但不知道是什么。有人可以解释一下我想要什么以及如何做到吗?

Tho*_*asK 6

您必须使用 NormalizerAwareTrait 才能访问书籍的规范化器

  • 添加接口
  • 使用特性
  • 为书籍调用 normalize() 方法

代码:

class UserNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    use NormalizerAwareTrait;

    public function normalize($object, $format = null, array $context = array())
    {
        return [
            'name' => $object->getName(),
            'books' => $this->normalizer->normalize($object->getBooks(), $format, $context)
        ];
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof User;
    }
}
Run Code Online (Sandbox Code Playgroud)