I am using php-di and Doctrine together. To use Doctrine there is a bootstrap.php
file which constructs the $entityManager
object. The $entityManager
object is defined globally in that file so to use it in my classes I have to inject it.
For example assume the class below:
<?php
interface IAccountService{
function login(string $username, string $password);
}
class AccountService implements IAccountService {
private $entityManager;
public function __construct($entityManager) {
$this->entityManager = $entityManager;
}
public function login(string $email, string $password){
$q = $this->entityManager->createQueryBuilder()
->select('us.id, us.name, us.email, us.passwordHashed')
->from('User', 'us')
->where('us.email = ?1 AND us.passwordHashed = ?2')
->setMaxResults( '1' )
->setParameter(1,$email)
->setParameter(2, HASHHELPER::hashPasswordSHA512($password, $email))
->getQuery();
// echo $q->getSql();
$users = $q->getResult();
// print_r($users);
if(!empty($users) && count($users) > 0){
$_SESSION["USER"] = $users[0];
return true;
}
else{
return false;
}
}
}
?>
But the type of $entityManager
is not well defined and either when I call echo gettype($entityManager);
it prints "object"
as result. So I think I need to inject this parameter by its name instead of its type. I mean something like this:
$container->set('$entityManager', $entityManager);
But this does not work. What's the solution and the best way?
The problem have solved after facing this link which shows the namespace and class name of
$entityManager
but the question of injecting according to variable name is still open. By now, the new source code of mine is like this:AccountService.php
routes.php