Skip to content

Instantly share code, notes, and snippets.

@alexsegura
Last active January 27, 2019 14:24
Show Gist options
  • Save alexsegura/6f319e92f3a74e685610 to your computer and use it in GitHub Desktop.
Save alexsegura/6f319e92f3a74e685610 to your computer and use it in GitHub Desktop.
Archivable pattern in Doctrine
<?php
use Doctrine\ORM\Mapping as ORM,
Doctrine\ORM\Event\LifecycleEventArgs;
/**
* @ORM\Table(name="item")
* @ORM\HasLifecycleCallbacks
*/
class Item
{
//
// Getters & setters here
//
/**
* Returns an instance of ItemArchive with all class properties copied.
* @param Item $item - the Item to copy properties from
* @return ItemArchive
*/
protected static function createArchive(Item $item)
{
$archive = new ItemArchive();
foreach (get_object_vars($item) as $key => $value) {
$setter = 'set' . ucfirst($key);
if (is_callable([$archive, $setter])) {
$archive->$setter($value);
}
}
return $archive;
}
/**
* @ORM\PreRemove
* Will be invoked when EntityManager::remove is called,
* to persist a copy of the Entity in the archive table.
*/
public function onPreRemove(LifecycleEventArgs $eventArgs)
{
$archive = self::createArchive($this);
$eventArgs->getEntityManager()->persist($archive);
}
}
<?php
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="item_archive")
*/
class ItemArchive
{
}
@kcassam
Copy link

kcassam commented Sep 27, 2018

I suggest class ItemArchive extends Item so you have the same properties

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment