I am trying to develop two authentication system in a single application. One for admin and another for user. I can connect to default database. But, I could not authenticate the user. I tried this code but its not working.
How to connect to another database from repository class?
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: ~
The simplest but not as clean solution would be:
# 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
}
Better solution would be to declare that repository class to be service and inject client entity manager object. (either via __constuct
or set*
method)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.