Doctrine 2 - Get Entity manager from class

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.

Answers


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 Auth class eventually.

Anyway I think that authorization doesn't need an external class - I'd just write a loginAction method 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.


Need Your Help

How do I retrieve data from a list<> containing class objects

c# list foreach

I want to retrieve data from a list I created that contains class objects via a foreach but I'm not able to.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.