Spiga

Zend Framework User Auth model

by Gabi Solomon

All 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.

PHP:
  1. class Users_Auth
  2. {
  3. private $_user;
  4.  
  5. public function  __construct()
  6. {
  7. $table = Users::instance();
  8.  
  9. if ($this->hasIndentity()) {
  10. $this->_user = $this->getIdentity();
  11. $this->_user->setTable($table);
  12. } else {
  13. $this->_user = $table->fetchNew();
  14. }
  15. }
  16.  
  17. public function get() {
  18. return $this->_user;
  19. }
  20.  
  21. public function set(Users_Row $user) {
  22. $this->_user = $user;
  23. Zend_Auth::getInstance()->getStorage()->write($user);
  24. }
  25.  
  26. private function hasIndentity()
  27. {
  28. return ($this->getIdentity() !== null);
  29. }
  30.  
  31. private function getIdentity()
  32. {
  33. return Zend_Auth::getInstance()->getIdentity();
  34. }
  35.  
  36. /**
  37. * Singleton pattern
  38. *
  39. * @staticvar Users_Auth $instance
  40. * @return Users_Auth
  41. */
  42. public function getInstance()
  43. {
  44. static $instance;
  45. if (!($instance instanceof Users_Auth)) {
  46. $instance = new Users_Auth();
  47. }
  48. return $instance;
  49. }
  50. }

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

blog comments powered by Disqus