Created
January 3, 2013 11:33
-
-
Save benlumley/4442866 to your computer and use it in GitHub Desktop.
Doctrine2 listener for use in SF2 to apply inheritance discriminator map based on DI parameters
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
# params - base | |
discriminator_map_bundle_ids: | |
mychildbundle1: 2 | |
mychildbundle2: 3 | |
# params in each child bundle | |
discriminator_map.mychildbundle1: | |
- { parent: 'My\BaseBundle\Entity\Entity1', child: 'My\ChildBundle1\Entity\Entity1' } | |
- { parent: 'My\BaseBundle\Entity\Entity2', child: 'My\ChildBundle1\Entity\Entity2' } | |
# listener service, in base | |
my.base.listener.addinheritancemappings: | |
class: My\BaseBundle\Doctrine\Listener\AddInheritanceMappings | |
arguments: [ %discriminator_map_bundle_ids%, @service_container ] | |
tags: | |
- { name: doctrine.event_listener, event: loadClassMetadata } | |
# Mapping in parent bundle | |
My\BaseBundle\Entity\Entity1: | |
type: entity | |
inheritanceType: SINGLE_TABLE | |
discriminatorColumn: | |
name: entity_type | |
type: integer | |
length: 11 | |
discriminatorMap: | |
0: MyEntity | |
# Child mapping | |
My\ChildBundle\Entity\Entity1: | |
type: entity |
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 | |
/** | |
* (c) Ben Lumley <[email protected]> | |
*/ | |
namespace My\BaseBundle\Doctrine\Listener; | |
use Doctrine\ORM\Event\LoadClassMetadataEventArgs; | |
class AddInheritanceMappings | |
{ | |
protected $bundle_ids; | |
protected $discriminator_map; | |
public function __construct($bundle_ids, $container) | |
{ | |
$this->bundle_ids = $bundle_ids; | |
foreach ($bundle_ids as $bundle => $id) { | |
if ($container->hasParameter('discriminator_map.' . $bundle)) { | |
$this->discriminator_map[$bundle] = $container->getParameter('discriminator_map.' . $bundle); | |
} | |
} | |
} | |
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) | |
{ | |
if (empty($this->discriminator_map)) { | |
return; | |
} | |
$metadata = $eventArgs->getClassMetaData(); | |
$class = $metadata->getName(); | |
foreach ($this->discriminator_map as $bundle=>$mappings) { | |
foreach ($mappings as $map) { | |
if ($class == $map['parent']) { | |
$metadata->addDiscriminatorMapClass($this->bundle_ids[$bundle], $map['child']); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment