Mohammad Naji
Mohammad Naji

Reputation: 5442

Where to put $user->logged_in() function? user_model or user_controller?

I've always put user authentication in application/models/user_model.php, but is that really the best place to put the function?

What makes me doubt about this way of coding, is that I've heard that, model should only work with database. So it means that session related things cannot be in model. Is that really so?

I make the function accessible via autoloading user_model model in config/autoload.php.

Upvotes: 1

Views: 186

Answers (1)

tereško
tereško

Reputation: 58444

It should be part of the model layer in real MVC and MVC-inspired design patterns, because logged-in would be a state of domain object, which the view should be examining through authentication/recognition service.

You might benefit from reading this post, but here is a quick hint - model is not tied to SQL database or any other specific storage medium. Session is just a different form of storage.

Unfortunately, CodeIgniter is not actually implementing MVC or MVC-inspired design patterns, but copying Rails. This means that, unless you want to implement a proper model layer in CI (which is not simple to do), you will have to perform this check in, what CodeIgniter refers to as, "controllers".


Update

You might want to look into way to place the authorization checks outside the controller (as described here). This way you would gain additional control over execution of code and wouldn't be "locked in" the chosen controller, when you detect, that current user has no permission to access a method.

If you do the authorization checks inside the controller, you end up redirection the client and you have to rewrite each controller, when something changes (thus, violating OCP).

Placing the initialization of authentication service and performance of authorization check outside the controller would not be against the ideas of MVC, because in definition of MVC the view is only responsible for changing the state of model layer and current view. There is nothing said about instantiating them. Therefore it is OK to initialize authentication service (which is part of model layer) before you perform action on the controller.

Upvotes: 3

Related Questions