How does Zend_Auth storage work?

John picture John · Sep 17, 2009 · Viewed 10.3k times · Source

This is very simple. I write

$auth->getStorage()->write($user);

And then I want, in a separate process to load this $user, but I can't because

$user = $auth->getIdentity();

is empty. Didn't I just... SET it? Why does it not work? Halp?

[EDIT 2011-04-13]

This has been asked almost two years ago. Fact is, though, that I repeated the question in July 2010 and got a fantastic answer that I back then simply did not understand.

Link: Zend_Auth fails to write to storage

I have since built a very nice litte class that I use (sometimes with extra tweaking) in all my projects using the same storage engine as Zend_Auth but circumventing all the bad.

<?php

class Qapacity_Helpers_Storage {

    public function save($name = 'default', $data) {

        $session = new Zend_Session_Namespace($name);
        $session->data = $data;

        return true;
    }

    public function load($name = 'default', $part = null) {

        $session = new Zend_Session_Namespace($name);

        if (!isset($session->data))
            return null;

        $data = $session->data;

        if ($part && isset($data[$part]))
            return $data[$part];

        return $data;
    }

    public function clear($name = 'default') {

        $session = new Zend_Session_Namespace($name);

        if (isset($session->data))
            unset($session->data);

        return true;
    }

}

?>

Answer

Gaston picture Gaston · Oct 19, 2009

It's supposed to work.

Here's the implementation of the Auth getIdentity function.

/**
 * Returns the identity from storage or null if no identity is available
 *
 * @return mixed|null
 */
public function getIdentity()
{
    $storage = $this->getStorage();

    if ($storage->isEmpty()) {
        return null;
    }

    return $storage->read();
}

Here's the implementation of the PHP Session Storage write and read functions:

/**
 * Defined by Zend_Auth_Storage_Interface
 *
 * @return mixed
 */
public function read()
{
    return $this->_session->{$this->_member};
}

/**
 * Defined by Zend_Auth_Storage_Interface
 *
 * @param  mixed $contents
 * @return void
 */
public function write($contents)
{
    $this->_session->{$this->_member} = $contents;
}

Are you sure you are loading the same instance of the Zend_Auth class?

Are you using

$auth = Zend_Auth::getInstance();

Maybe you are calling the write method after the getIdentity method?

Anyway, as I said before, what you are doing should work.