Last active
January 27, 2019 14:24
-
-
Save alexsegura/6f319e92f3a74e685610 to your computer and use it in GitHub Desktop.
Archivable pattern in Doctrine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Doctrine\ORM\Mapping as ORM; | |
/** | |
* @ORM\Table(name="item_archive") | |
*/ | |
class ItemArchive | |
{ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suggest
class ItemArchive extends Item
so you have the same properties