Valentin Golev
Valentin Golev

Reputation: 10095

Can (and should?) Zend_Auth return class as the Identity?

I have a class R00_Model_User, which, curiously enough, represents user as he is. Can $result->getIdentity() return me an object of this class? (Or maybe it's stupid?)

(There is a factory method in R00_Model_User which prevents from duplicating objects. I'd like Zend_Auth to use it instead of creating a new object, if it can)

Upvotes: 0

Views: 438

Answers (2)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

Two options:

  • write your own authentication adapter subclassing the out-of-the-box-adapter that matches your scenario best

    class R00_Auth_Adapter extends Zend_Auth_Adapter_*
    {
        /**
         * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
         * attempt an authentication.  Previous to this call, this adapter would have already
         * been configured with all necessary information to successfully connect to a database
         * table and attempt to find a record matching the provided identity.
         *
         * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
         * @return Zend_Auth_Result
         */
        public function authenticate()
        {
            $result = parent::authenticate();
            if ($result->isValid() {
                return new Zend_Auth_Result(
                    $result->getCode(),
                    R00_Model_User::load($result->getIdentity()),
                    $result->getMessages()
                );
            } else {
                return $result;
            }
        }
    }
    

    This will allow you to code

    $adapter = new R00_Auth_Adapter();
    //... adapter initialisation (username, password, etc.)
    $result = Zend_Auth::getInstance()->authenticate($adapter);
    

    and on successfull authentication your user-object is automatically stored in the authentication storage (session by default).

  • or use your login-action to update the stored user identity

    $adapter = new Zend_Auth_Adapter_*();
    $result = $adapter->authenticate();
    if ($result->isValid()) {
        $user = R00_Model_User::load($result->getIdentity());
        Zend_Auth::getInstance()->getStorage()->write($user);
    }
    

Upvotes: 2

Eugene M
Eugene M

Reputation: 1307

In one of my applications, I have getIdentity() return a user object, and it works pretty well for me. To use your factory method, do like this:

$auth = Zend_Auth::getInstance();
$user = R00_Model_User::getInstance(...);
$auth->getStorage()->write($user);

Then when you call getIdentity(), you will have your user object.

Upvotes: 0

Related Questions