我有一个帮助服务,可以将我动态链接到数据库。
$databaseName = 'db_x';
$em = $this->entityManagerProvider->get($databaseName);
我可以这样使用这个实体管理器:
$car = new Car();
$car->setName('Audi');
$em->persist($car);
$em->flush();
效果很好!对象已插入我的db_x
但是如果我在此实体管理器上运行存储库方法:
$em->getRepository('App\Entity\Car')->findById(1);
然后,实体管理器尝试在我的默认数据库而不是db_x上运行。怎么可能?
我切换数据库的服务:
namespace App\Utils\Database;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
class EntityManagerProvider
{
/**
* @var EntityManagerInterface
*/
protected $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
/**
* @param $databaseName
* @return EntityManagerInterface
* @throws \Doctrine\ORM\ORMException
*/
public function get($databaseName): EntityManagerInterface
{
return EntityManager::create(
$this->configureParams($databaseName),
$this->entityManager->getConfiguration(),
$this->entityManager->getEventManager()
);
}
/**
* @param string $databaseName
* @return array
*/
private function configureParams(string $databaseName): array
{
$params = $this->entityManager->getConnection()->getParams();
unset(
$params['dbname'],
$params['path'],
$params['url'],
$params["wrapperClass"]
);
$params['dbname'] = $databaseName;
return $params;
}
}