Zend Framework User Auth model
by Gabi SolomonAll of the applications this days will involve a database to store data and most of them will also have a user system. This means that beside building a login/register page you also need a method to store the data of the logged-in user while they are logged in.
Normally in php driven websites you will have that data storred in sessions, but in Zend Framework its easyer to use Zend_Auth to help you manage that part for you. The way i implemented my login is that i save the the user model in Zend_Auth storage, this helps me by having acces to the models methods like isAdmin for example.
Although this is so far pretty ok, i dont really like calling Zend_Auth to get the current user all the time, plus i would enjoy to have an empty user model returned if no user is logged in. This is why i wrote a small model that i named Users_Auth.
-
class Users_Auth
-
{
-
private $_user;
-
-
public function __construct()
-
{
-
$table = Users::instance();
-
-
if ($this->hasIndentity()) {
-
$this->_user = $this->getIdentity();
-
$this->_user->setTable($table);
-
} else {
-
$this->_user = $table->fetchNew();
-
}
-
}
-
-
public function get() {
-
return $this->_user;
-
}
-
-
public function set(Users_Row $user) {
-
$this->_user = $user;
-
Zend_Auth::getInstance()->getStorage()->write($user);
-
}
-
-
private function hasIndentity()
-
{
-
return ($this->getIdentity() !== null);
-
}
-
-
private function getIdentity()
-
{
-
return Zend_Auth::getInstance()->getIdentity();
-
}
-
-
/**
-
* Singleton pattern
-
*
-
* @staticvar Users_Auth $instance
-
* @return Users_Auth
-
*/
-
public function getInstance()
-
{
-
static $instance;
-
if (!($instance instanceof Users_Auth)) {
-
$instance = new Users_Auth();
-
}
-
return $instance;
-
}
-
}
The use is quite easy to understand, you just call Users_Auth::getInstance()->get(); to have the current logged user.
If you look in the construct you will see this line $this->_user->setTable($table); that is there because for some reason ( if you can figure it out pls tell me in the comment section ) after storing the model in Zend_Auth it looses connection with the model table.
That is it, not a very complicated post, just something that makes my coding just a little easyer.
Cheers.
Related Posts
-
Gabi Solomon
-
stormwild

