all. Here is the situation, I have php page, which is doing some register, login, these kind of thing that related to user, so, let call it user.php.
In the user.php, I have a user class have following methods:
-public static function register($aEmail, $aPassword)
-public static function login($aEmail, $aPassword)
-public static function logout($aEmail, $aSessionKey)
So, when the user login, I will do something like this:
if(isset($_POST["email"]) && isset($_POST["password"]) && isset($_POST["action"])){
$email = htmlspecialchars($_POST["email"]);
$password = htmlspecialchars($_POST["password"]);
if($_POST["action"] == login){
$user = new User();
//It will print the session key
$user->doLoginAndPrintTheSessionKey($email, $password);
}
It works great, but the question is, should I make the User as a object or a singleton only,开发者_Python百科 seems there is not point to keep a User object, because when user make a request, I need use his email and session key to find deal with his records.....
like this..
public static function postAComment($aEmail, $aSessionKey, $aCommment){
BOOL $isSuccess = FALSE;
//check the session key is valid or not
if(self::isUserValidationValid($aEmail, $aSessionKey)){
//make a sql statement that write aComment to DB
//execute the sql statement
//if execute success, return isSuccess = TRUE;
}
return $isSuccess;
}
As you can see, I can do all this in a singleton class, so, my question is... ...Is there no need to make a useer object in this situation? Thank you.
You should crate an User class but it shouldn't be a singleton.
Having User object would simplify your API. You would have:
register( $aPassword )
login( $aPassword )
logout( $aSessionKey )
Instead of:
register($aEmail, $aPassword)
login($aEmail, $aPassword)
logout($aEmail, $aSessionKey)
You pass $aEmail through constructor.
Applying the singleton pattern adds no benefits here. It seldomly does in a scripting language like PHP. You accomplish nothing by adding the extra logic required to simulate a singleton (PHP does not allow for real ones anyway).
And lastly there might be circumstances where you might want to create two user objects after all. Think of an administration tool that allows to scan for duplicate user accounts. That's probably not high up on your list, and probably pointless for most websites, but you cannot completely rule out that you somewhen might need to utilize your user class this way.
The thing with "Singletons" is that they have a catchy name, but not a whole lot of applications. Just forget about it. http://sites.google.com/site/steveyegge2/singleton-considered-stupid
But I guess your main question was about just using a static method to handle everything. And yes, that makes sense. If you do not actually have a use case to instantiate a user object, then don't. Create a utility method if that is what you can get away with. http://en.wikipedia.org/wiki/KISS_principle
精彩评论