我正在尝试在单个应用程序中开发两个身份验证系统。一个用于管理员,另一个用于用户。我可以连接到默认数据库。但是,我无法验证用户身份。我尝试了这段代码,但它没有用。
如何从存储库类连接到另一个数据库?
UserRepository.php
class UserRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$request = Request::createFromGlobals();
//print_r($request);
$company_id = $request->get('_company_code');
$conn = $this->getEntityManager('client')->getConnection();
$query = $conn
->createQueryBuilder('u')
->where('u.username = :username AND u.company_id= :company_id')
->setParameter('username', $username)
->setParameter('company_id', $company_id);
//->getQuery();
try {
// The Query::getSingleResult() method throws an exception
// if there is no record matching the criteria.
$user = $query->getFirstResult();
//$user = $query->getSingleResult();
//exit("123");
} catch (NoResultException $e) {
$message = sprintf(
'Unable to find an active admin AcmeUserBundle:User object identified by "%s".',
$username
);
throw new UsernameNotFoundException($message, 0, $e);
}
return $user;
}
Config.yml
doctrine:
dbal:
default_connection: default
connections:
default:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
client:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name2%"
user: "%database_user2%"
password: "%database_password2%"
charset: UTF8
orm:
default_entity_manager: default
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
connection: default
mappings:
ESSCompanyBundle: ~
ESSAdminUserBundle: ~
ESSUserBundle: ~
client:
connection: client
mappings:
ESSUserBundle: ~
答案 0 :(得分:0)
最简单但不那么干净的解决方案是:
# Controller code
$repo = ....
$repo->setClientEntityManager( $clientEntityManager );
# Repo code
public function setClientEntityManager(){
$this->clientEntityManager = $clientEntityManager;
}
public function someRepoFunction(){
$this->clientEntityManager-> // you do here whatever you'd like
}
更好的解决方案是将存储库类声明为服务并注入客户端实体管理器对象。 (通过__constuct
或set*
方法)