Oleg Patrushev
Oleg Patrushev

Reputation: 265

Doctrine 2 entity hydrator

Is there way to hydrate entity data like as after doctrine query

$entityData = $this->entityService->find($id)->getArrayResult();

and do it if you already have entity

$entity = $this->entityService->find($id)->getOneOrNullResult();
$entityData = $SomeDoctrineService->entityToArray($entity);

Solution

Firstly you can use \DoctrineModule\Stdlib\Hydrator\DoctrineObject

$hydrator = DoctrineObject(
        $entityManager,
        get_class($entity)
    );

$entityData = $hydrator->extract($entity);

and secondly I've added custom hydrator trait EntityDataTrait

use Doctrine\ORM\Proxy\Proxy;
trait EntityDataTrait
{
    /**
     * @return array
     */
    public function toArray()
    {
        $data = get_object_vars($this);

        if ($this instanceof Proxy) {
            $originClassName = get_parent_class($this);

            foreach ($data as $key => $value) {
                if (!property_exists($originClassName, $key)) {
                    unset ($data[$key]);
                }
            }
        }

        foreach ($data as $key => $value) {
            if (method_exists($this, 'get' . ucfirst($key))) {
                $data[$key] = $this->{'get' . ucfirst($key)}();
            }
        }

        return $data;
    }
}

for example

class MyEntity {
  use EntityDataTrait;

  /*properties and methods below*/
}

$entity = new MyEntity();
$entityData = $entity->toArray();

Upvotes: 1

Views: 1223

Answers (1)

Stepashka
Stepashka

Reputation: 2698

I'm afraid there is no built in doctrine functionality for this. You should create your own serializer or use one of existent ones: JMS Serializer, Symfony Serializer.

You can create your own serializer as well. Sample code could be found here Doctrine2 export entity to array but it was mentioned that it is not the best approach.

Upvotes: 1

Related Questions