I can’t figure out how it is best to get the Doctrine Entity Manager from my service layers, and template controller..
I thinking of making a singleton so i always can get the Entity manager, but is it the right way to do it?
Updated: I’ll take an example
class Auth
{
const USER_ENTITY_NAME = 'Entities\User';
private $isVerified = FALSE;
public static function login($email, $password, $em, $rememberMe = false)
{
if(empty($email) OR empty($password))
{
// new login response
}
if($user = (self::getUser($email, $password, $em) !== null))
{
$sreg = SessionRegistry::instance();
$sreg->set("user_id", $user->getId());
}
return $user;
}
public static function getUser($email, $password, $em)
{
return $em->getRepository(
USER_ENTITY_NAME );
}
What i cant figure out is where i should get the user from? so i doesn’t have to send the entity manager as an parameter.
Choose dependency injection over singleton.
I don’t know which environment are you using Doctrine in, but I assume it being MVC – then any Controller should have access to the entity manager, either by passing it as a constructor argument, either by injecting it with a setter.
This way you can fetch stuff from the controller, and pass it to the
Authclass eventually.Anyway I think that authorization doesn’t need an external class – I’d just write a
loginActionmethod in a controller, get username and password from HTTP request and make the usual considerations [fetch the user / check if password is right], then store something in session in case of succesful login.