Skip to content

Instantly share code, notes, and snippets.

@jeremykendall
Last active August 29, 2015 14:27
Show Gist options
  • Save jeremykendall/442b840df76ffca72a8d to your computer and use it in GitHub Desktop.
Save jeremykendall/442b840df76ffca72a8d to your computer and use it in GitHub Desktop.
Doctrine2 EntityManager via Aura.Di using wrapper and factory
<?php
namespace Namespace\Di;
use Aura\Di\Config;
use Aura\Di\Container;
use Doctrine\Common\Cache\ApcCache;
use Doctrine\Common\Cache\ArrayCache;
use Doctrine\DBAL\Event\Listeners\MysqlSessionInit;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
class DoctrineConfig extends Config
{
public function define(Container $di)
{
parent::define($di);
// ... snip ...
$di->params['Namespace\EntityManagerFactory'] = [
'connectionOptions' => $connectionOptions, // array
'config' => $config, // Doctrine\ORM\Configuration
'eventManager' => null,
];
$di->set('entityManager', $di->lazy(function () use ($di) {
$factory = $di->newInstance('Namespace\EntityManagerFactory');
return $factory();
}));
}
public function modify(Container $di)
{
parent::modify($di);
$di->get('entityManager')->getEventManager()->addEventSubscriber(
new MysqlSessionInit('utf8', 'utf8_unicode_ci')
);
}
protected function getCacheImpl()
{
if (APP_MODE === 'development') {
return new ArrayCache();
}
return new ApcCache();
}
protected function shouldAutoGenerateProxies()
{
return (APP_MODE === 'development');
}
}
<?php
namespace Namespace;
use Doctrine\Common\EventManager;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager;
class EntityManagerFactory
{
public function __construct(
array $connectionOptions,
Configuration $config,
EventManager $eventManager = null
) {
$this->conn = $connectionOptions;
$this->config = $config;
$this->eventManager = $eventManager;
}
public function __invoke()
{
$entityManager = EntityManager::create(
$this->conn,
$this->config,
$this->eventManager
);
return $entityManager;
}
}
<?php
// Default EntityManager
$em = $di->get('entityManager');
// Grab a new EntityManager (because I still can't use $di->newInstance('entityManager'))
// Not happy with the duplication, but it works
// MAKE IT WORK, REFACTOR! :-)
$newEm = function () use ($di) {
$factory = $di->newInstance('Namespace\EntityManagerFactory');
return $factory();
};
// If EntityManager is closed due to transaction issue, grab a new one
$em = $newEm();
@harikt
Copy link

harikt commented Aug 18, 2015

As you will be getting different instances of entity manager. I feel this https://gist.github.com/jeremykendall/442b840df76ffca72a8d/446a2f79019e0ecb87679cee88728f26119b5225#file-doctrineconfig-php-L38-L40 line should be moved inside to the Factory.

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