如何使用(链?)多个规范化器与Symfony Serializer?

时间:2017-09-04 16:38:58

标签: php symfony serialization serializer

在使用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;
    }
}

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

$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();

假设我还想在序列化书籍时包含哈希值,所以我有以下规范化程序:

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;
    }
}

我得到了预期的结果: {"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;
    }
}

现在,使用之前给定的规范化器对书籍进行规范化,我得到以下结果: {"name":"Person name","books":[{},{}]}

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

我想我误解了关于规范化的东西,但不知道是什么。有人可以解释我想要什么,怎么做?

0 个答案:

没有答案