views:

167

answers:

2

I'm developing my own PHP framework, and I'm trying to do things more "by the book".

I want to build login system. I have done this plenty of times, but now I just want to confirm/get some feedback on a system.

I know we need...

  • A Session Object
  • A User Object
  • A Login Controller

What my question is, is who holds what power?

Here's my thought - when you submit your un/pw, it obviously goes to the Login Controller. We need to look up that un/pw combo in the user database, and therefore I feel as if that should be done in the in the user object ... $User->authenticate($un, $pw).

All that should do i return true or false. Then the LoginController should tell the Session object to create a session ... $session->create(). But apart of me wonders if the User and Session object should be a bit closer knit, and not rely on a Controller.

Looking for opinions, thanks in advance.

A: 

My thoughts for a framework like this:

Initialize session object on page loads, and set it to default to a "guest account".

Upon this initialization make your session object to look for a session identifier (from a cookie?) and validate that ID against your session tracking back-end, be it database or whatever you are using.

If the session ID validates, you get your relevant user ID which you can then use to populate the user object.

Login control should just authenticate the user from login, and initialize the session by binding session ID and user ID on the back end, and by writing the session ID to a cookie.

... A more efficient way, however, would be to authenticate the user once and write the user ID to a digitally signed cookie set by the server, and trust all valid cookies returned by the client. This would make session management so much lighter and save round trips do database.

nnevala
+2  A: 

In my opinion, the user object shouldn't know about persistence (session) or the application (controllers). All it should care for is representing a user and handling user-related functions like authenticate.

The controller is all about application logic, and the session is part of the application. I feel like it's the controllers task to open the session and store the user object for later usage, once authenticated.

P.s. Did you publish your framework? Github it! :-D

Mario
I agree with this. In my framework -- which is on GitHub ;) http://github.com/apinstein/phocoa -- login is separate from the model. The app defines login, and you build a delegate to check credentials against the model. It's worked really well in practice. Feel free to check out the source.
apinstein
Yea, since PHP is mostly web-related, often you get the urge to merge a couple of different things together for convenience (or re-usability), which isn't totally wrong I believe, it just depends of the context.
Mario