Doctrine2出口实体阵列(Doctrine2 export entity to array)

2019-08-03 02:10发布

我有Product实体与许多-to-one的Category实体。 我需要存储Product的会话。 首先,我试图实现\Serializable的产品界面。 我应该如何序列化我相关Category的实体? 是否也应该实现\Serializable界面?

我阅读,系列化的教义是非常痛苦的操作,我想这个问题:

我们可以从实体获取原始值? 正是这样的数据,其存储在数据库中。 如果我们能得到这个值,我们可以在任何地方保存并重新创建对象!

我读doctrine2代码,并找到方法Doctrine\ORM\Internal\Hydration\ObjectHydrator:hydrateRowData但它的保护。 是否有这样做的任何公开的API?

更新:

我只是copypaste和整合来自BasicEntityPersister一些代码,它似乎工作。

    $product = $productsRepository->find($id);

    if (!$product) {
        throw $this->createNotFoundException('No product found for id ' . $id);
    }

    $uow = $em->getUnitOfWork();
    $entityPersister = $uow->getEntityPersister(get_class($product));
    $classMetadata = $entityPersister->getClassMetadata();

    $originalData = $uow->getOriginalEntityData($product);

    $result = array();
    foreach ($originalData as $field => $value) {
        if (isset($classMetadata->associationMappings[$field])) {
            $assoc = $classMetadata->associationMappings[$field];

            // Only owning side of x-1 associations can have a FK column.
            if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & \Doctrine\ORM\Mapping\ClassMetadata::TO_ONE)) {
                continue;
            }

            if ($value !== null) {
                $newValId = $uow->getEntityIdentifier($value);
            }

            $targetClass = $em->getClassMetadata($assoc['targetEntity']);
            $owningTable = $entityPersister->getOwningTable($field);

            foreach ($assoc['joinColumns'] as $joinColumn) {
                $sourceColumn = $joinColumn['name'];
                $targetColumn = $joinColumn['referencedColumnName'];

                if ($value === null) {
                    $result[$owningTable][$sourceColumn] = null;
                } else if ($targetClass->containsForeignIdentifier) {
                    $result[$owningTable][$sourceColumn] = $newValId[$targetClass->getFieldForColumn($targetColumn)];
                } else {
                    $result[$owningTable][$sourceColumn] = $newValId[$targetClass->fieldNames[$targetColumn]];
                }
            }
        } elseif (isset($classMetadata->columnNames[$field])) {
            $columnName = $classMetadata->columnNames[$field];
            $result[$entityPersister->getOwningTable($field)][$columnName] = $value;
        }
    }

    print_r($result);

$result ,我们有原始值。 现在,我们需要的方式如何通过这个数组来创建对象

Answer 1:

<?php

namespace Acme\ServiceBundle\Services;

use Doctrine\ORM\EntityManager;

class EntitySerializer
{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function serialize($entity)
    {
        $className = get_class($entity);

        $uow = $this->em->getUnitOfWork();
        $entityPersister = $uow->getEntityPersister($className);
        $classMetadata = $entityPersister->getClassMetadata();

        $result = array();
        foreach ($uow->getOriginalEntityData($entity) as $field => $value) {
            if (isset($classMetadata->associationMappings[$field])) {
                $assoc = $classMetadata->associationMappings[$field];

                // Only owning side of x-1 associations can have a FK column.
                if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & \Doctrine\ORM\Mapping\ClassMetadata::TO_ONE)) {
                    continue;
                }

                if ($value !== null) {
                    $newValId = $uow->getEntityIdentifier($value);
                }

                $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
                $owningTable = $entityPersister->getOwningTable($field);

                foreach ($assoc['joinColumns'] as $joinColumn) {
                    $sourceColumn = $joinColumn['name'];
                    $targetColumn = $joinColumn['referencedColumnName'];

                    if ($value === null) {
                        $result[$sourceColumn] = null;
                    } else if ($targetClass->containsForeignIdentifier) {
                        $result[$sourceColumn] = $newValId[$targetClass->getFieldForColumn($targetColumn)];
                    } else {
                        $result[$sourceColumn] = $newValId[$targetClass->fieldNames[$targetColumn]];
                    }
                }
            } elseif (isset($classMetadata->columnNames[$field])) {
                $columnName = $classMetadata->columnNames[$field];
                $result[$columnName] = $value;
            }
        }

        return array($className, $result);
    }

    public function deserialize(Array $data)
    {
        list($class, $result) = $data;

        $uow = $this->em->getUnitOfWork();
        return $uow->createEntity($class, $result);
    }
}


Answer 2:

我有同样的问题,我也想有关联的数据数组中了。 所以,我想出了以下内容:

$serializer = new Serializer($this->em); // Pass the EntityManager object
$array = $serializer->serialize($message); // Returns the array (with associations!)

资源:

<?php

/**
 * Class Serializer
 *
 * @author Steffen Brem
 */
class Serializer
{
    /**
     * @var Doctrine\ORM\EntityManager
     */
    private $_em;

    /**
     * Constructor
     *
     * @param \Doctrine\ORM\EntityManager $em
     */
    public function __construct(\Doctrine\ORM\EntityManager $em)
    {
        $this->_em = $em;
    }

    /**
     * Serialize entity to array
     *
     * @param $entityObject
     * @return array
     */
    public function serialize($entityObject)
    {
        $data = array();

        $className = get_class($entityObject);
        $metaData = $this->_em->getClassMetadata($className);

        foreach ($metaData->fieldMappings as $field => $mapping)
        {
            $method = "get" . ucfirst($field);
            $data[$field] = call_user_func(array($entityObject, $method));
        }

        foreach ($metaData->associationMappings as $field => $mapping)
        {
            // Sort of entity object
            $object = $metaData->reflFields[$field]->getValue($entityObject);

            $data[$field] = $this->serialize($object);
        }

        return $data;
    }
}


文章来源: Doctrine2 export entity to array