Sep 28 2012

Cloning proxied Doctrine 2 entities

Simply using $cloned = clone $proxy; and persisting does not work.

To get round this, you can do the following (contrived example ahoy):

$user = $em->find('User', 1);

$clonedUser = clone $user;

$addressRef = $user->getAddress()->getRef();

// remove address proxy from identity map to ensure we get actual entity
$em->getUnitOfWork()->removeFromIdentityMap($user->getAddress());

$address = $em->find('Address', $addressRef);

$clonedAddress = clone $address;

$clonedUser->setAddress($clonedAddress);

There is definitely a better way of doing this, after trying different approaches and a fair amount of googling I haven't found one though.

Any comments, criticisms or alternative solutions welcomed!

comments powered by Disqus

Info

I'm Ade Slade, a PHP web developer.