Search code examples
phpdesign-patternsdaofactory-pattern

Creating a model instance of a user based on an open session


I'm following the Data Access Object pattern, along with Factory (edit: sorry if I'm doing noob mistakes).

To log in a User, I currently do:

$user_dao = UserDaoFactory::getUserDaoFactory()->getUserDao();
$user = $user_dao->create($_POST['email'], $_POST['password']);
if ($user_dao->authenticate($user))
{
    $user_dao->login($user); // sets $_SESSION['id']
}

My question is for consequent pages. Given that the user is in effect logged in, how should I go about creating and accessing an instance of their User model?

To get an instance of the logged in user, should I do something like the following?

To continue the session on the next page, should I try the following?

$user_dao = UserDaoFactory::getUserDaoFactory()->getUserDao();
$user = $user_dao->userFromSession($_SESSION['id']);
if ($user->isLoggedIn()) {
    // success
}

I would have to do this every place I need to know something about the currently logged in user.

Or try this other approach?

Or should I be abstracting the "give me an instance of the logged in user model" to something like a user Factory?

For example, storing an instance of the logged in User in a private static property of a User class?

class User {
    /* ... */
    private static $_logged_in_user;
    
    public static function setUserLoggedIn(User $user)
    {
        self::$_logged_in_user = $user;
    }
    
    public static function getLoggedInUser() {
        if (!self::$_logged_in_user)
    {
        self::$_logged_in_user = new self;
    }
    return self::$_logged_in_user;
    }
    /* ... */
}
$user = User::getLoggedInUser();

Solution

  • You should create a separate class for authorization purpose, logging in method should not belong to user model. Kohana framework implements this quite well - check out this link just to get a basic idea: http://kohanaframework.org/3.2/guide/api/Auth.