Ali
Ali

Reputation: 7493

IN MVC - is session handling & authentication to be handled by User Model?

I was wondering if session handling like authentication and signing in is best handled by the User Model (assuming a user model refers to a user) and has attributes such as email and password. Or should session handling be held by another model?

What exactly is the best way to do this - I have code pretty much strewn partially in controllers in function files and want to refactor my code to adhere more to MVC principles. My project is based on the Zend Framework.

Upvotes: 3

Views: 198

Answers (2)

David Weinraub
David Weinraub

Reputation: 14184

I view authentication and session management as application-level concerns.

One general criterion I often apply is this: "Could I use my models in another app (perhaps a commandline app) or another website?

For example, in your circumstance, I would view a User model as representing a user. That user exists irrespective of whether or not he is actually visiting and/or logging in/out of your website. He could be referenced in a commandline app (Ex: a cron job that sends email to all users on their birthday; a reporting utility that counts all users that have incomplete profiles); etc. As such, I would keep authentication session management at the controller-level or perhaps one level down in a service level.

But as in most things, YMMV.

Upvotes: 1

BADAOUI Mohamed
BADAOUI Mohamed

Reputation: 2214

In MVC concept, the model represents the business part of your application.

Manage authentication, saving, deleting, activating of an user are business issues.

So it makes sense to create a method authenticate, save, delete, activate directly in your user model.

So in your user model, it is preferable to implement static methods as

public static function authenticate ($ username, $ password)
{
     $authService = $this-> getServiceLocator()->get('Zend\Authentication\AuthenticationService');
     $adapter = $authService->getAdapter();
     $adapter->setIdentityValue($username);
     $adapter->setCredentialValue($password);
     $authResult = $authService->authenticate();

     return $authResult->isValid();
}

And in your controller, you can directly do:

User/Entity/User::authenticate($username, $password);

Upvotes: 1

Related Questions