I’ve got a class:
AuthenticationService
-
findLoggedInUser()
Checks session if User is logged in. If not, check client persistent user login cookie and log in.
-
loginUser($email, $pw, $remember = false)
Log User in, and if
$remember
is true create persistent login cookie for User and a record for it in the database. -
logoutUser()
Removes User from the session, and any User persistent login cookie from the client and corresponding record in the database.
And I figured that I should separate this class into two different classes; one that handles the session part and one for the cookie part. So I would pretty much end up with two classes with more or less the same methods, but taking care of a different responsibility.
What would be the best way to combine those together, as if I would have a single AuthenticationService
class?
Think about the level of abstraction.
A developer who uses AuthenticationService
class doesn’t care if, under the hood, the class is using cookies, session, database or some magical parameters within an URI. It makes sense to have both findLoggedInUser()
and loginUser()
in the same class.
The class itself, on the other hand, relies on a lower abstraction: it may know whether it should use cookies or session, but doesn’t care about the actual underlying mechanism (such as how sessions are handled: all that matters is to be able to get and set session variables).
This means that you can keep AuthenticationService
and create two additional classes:
-
class
AuthenticationCookieHandler
void CreateCookie(User user)
UserId FindUser()
-
class
Session
bool IsAuthenticated()
User FindCurrentUser()
void AssignUser(User user)
void Reset()
2