Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
register doctrine extension in zf2 doctrine module
<?php
namespace Common\Service;
use Doctrine\ORM\EntityManager;
use DoctrineModule\Service\AbstractFactory;
use Zend\ServiceManager\ServiceLocatorInterface;
class EntityManagerFactory extends AbstractFactory
{
/**
* {@inheritDoc}
* @return EntityManager
*/
public function createService(ServiceLocatorInterface $sl)
{
/* @var $options \DoctrineORMModule\Options\EntityManager */
$options = $this->getOptions($sl, 'entitymanager');
$connection = $sl->get($options->getConnection());
$config = $sl->get($options->getConfiguration());
// initializing the resolver
// @todo should actually attach it to a fetched event manager here, and not
// rely on its factory code
$sl->get($options->getEntityResolver());
// Table Prefix
$tablePrefix = new \Common\DoctrineExtension\TablePrefix('prefix_');
$evm = $connection->getEventManager();
$evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
return EntityManager::create($connection, $config, $evm);
}
/**
* {@inheritDoc}
*/
public function getOptionsClass()
{
return 'DoctrineORMModule\Options\EntityManager';
}
}
<?php
return array(
'doctrine_factories' => array(
'entitymanager' => 'Common\Service\EntityManagerFactory',
),
);
<?php
namespace Common\DoctrineExtension;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
class TablePrefix
{
protected $prefix = '';
public function __construct($prefix)
{
$this->prefix = (string) $prefix;
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
$classMetadata = $eventArgs->getClassMetadata();
$classMetadata->setTableName($this->prefix . $classMetadata->getTableName());
foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {
$mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
$classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment