Here is the basic structure of my User class:
class User {
private $_userId = NULL;
private $_isAuthenticated = FALSE;
private $_code = NULL;
private $_pageLoads = 1;
private $_dbh = NULL;
const SECRET = 'shhhh its a secret';
const PAGE_LOADS = 5;
const HALF_SECOND_MS = 500000;
function __construct( PDO $dbh ) {
$this->_dbh = $dbh;
}
开发者_Go百科
public function login( $username, $password ) {}
public function isAuthenticated() {}
private function _authenticate( $username, $password ) {}
private function _challenge() {}
private function _generateCode() {}
private function _protectedVars() {}
function __sleep() {}
function __wakeup() {}
public function save() {
return serialize( $this );
}
}
DESCRIPTION OF WHAT I'M TRYING TO DO
I've been for quite some time using the PHP built in mysql functions. I've decided for this project that I'd follow a more OOP approach and move to PDO. When I used to build a "secure" environment I would have a login form, check if the user existed (with the correct password) and then save the user id in a session variable (say: $_SESSION['user_id']) and voila. In my secure env. I would simply check if user_id was set and I'd give them access.
Now I know this wasn't a very good approach, and I know the code above will probably have its own problems (which I hope you guys will give me hell for it for educational purposes). Basically my idea was to create a User object where I'd pass my PDO object in the constructor. From this user I could login and once all execution was done I'd save the user in a session variable by serializing the class. Once a new page would load the wake up function would get called and I'd callenge the data that's unserialized to make sure it wasn't tampered with, in which case, I'd log off the user by turning the isAuthenticated flag off (that's the code above).
QUESTION
When I try to serialize the object I get an error telling me that PDO objects cannot be serialized. I did a bit of research and see that I would have to implement the __sleep method and return an array of variables I'd want to save. However, when I wake up how do I reinitialize the PDO object within the user object? Is there a method where I can add arguments to the unserialize function which would pass it down to my __wakeup function? Am I completely on the wrong track and need to rethink this?
You should be able to get your PDO object from something like MyApp::getConnection()
and call it from your __wakeup method
精彩评论