目前我正在使用Doctrine 2处理ZF2应用程序。该应用程序处理多个用户,每个用户都可以通过自己的子域访问应用程序,例如:
user1.example.com
user2.example.com
...
user10.example.com
此外,每个用户都有自己的数据库,对应于他的子域名,请说:
db_user1
db_user2
..
db_user10
配置非常简单,只有一个或两个学说连接:
<?php
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'user',
'password' => 'pass',
'dbname' => 'database',
)
),
// Here we can define several configuration alternatives,
//use different keys for each one
'orm_alternative'=> array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'db_user1',
'password' => 'db_pass1',
'dbname' => 'db_user1',
)
),
),
)
);
显然在我的情况下,上面的配置是无用的,因为我有不确定数量的连接到不同的数据库。
所以,我的问题是什么是基于子域设置Doctrine以使用无限数量连接的最佳方法。
干杯,
瓦西里达科夫答案 0 :(得分:0)
配置加载顺序看起来像那样
1.application.config.php
2.$module->getConfig()
3.$module->get{,*}Config() (or ServiceListeners)
4./config/autoload/{,.*}{global,local}.php
因此,您可以在Module.php
函数的getConfig()
中添加每个用户配置。
public function getConfig()
{
return array(
'user1' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => 'db_user1',
'password' => 'db_pass1',
'dbname' => 'db_user1',
)
)
);
//of course you have access to service locator here and could generate your dbconfigs
}
答案 1 :(得分:0)
我认为我自己问题的最佳解决方案是通过Service Factory获取EntityManager实例,如下例所示:
<?php
namespace Application\Doctrine\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
class EntityManagerServiceFactory implements FactoryInterface {
public function createService(ServiceLocatorInterface $serviceLocator)
{
$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST']));
$paths = array(ROOT_PATH.'/module/Application/src/Application/Entity');
$account => $this->getAccountTable()->findOneBy(array("subdomain" => $subdomain));
$isDevMode = true;
$dbParams = array(
'driver' => 'pdo_mysql',
'user' => $account['user'],
'password' => $account['password'],
'dbname' => $account['dbname'],
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$config = Setup::createConfiguration($isDevMode);
$driver = new AnnotationDriver(new AnnotationReader(), $paths);
AnnotationRegistry::registerLoader('class_exists');
$config->setMetadataDriverImpl($driver);
$entityManager = EntityManager::create($dbParams, $config);
return $entityManager;
}
}
它工作正常,希望能帮助别人。