编辑用户后更新Zend_Auth存储

3

我使用Zend_Auth对用户进行身份验证,然后将其详细信息存储在默认的Zend_Auth会话中。这意味着当用户编辑其详细信息时,这些更改不会在应用程序中反映出来,直到他重新进行身份验证。

我希望避免这个问题的方法如下:

  1. When the user logs in we only store his user ID in a Zend_Auth session
  2. On each request we fetch the user's details from the database in a preDispatch() hook, using the user ID which was stored upon login in the Zend_Auth session:

    class Plugin_Auth extends Zend_Controller_Plugin_Abstract
    {
    
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            if ($auth->hasIdentity())
            {
                $id = $auth->getIdentity()->id;
    
                $userModel = new Model_User();
    
                $user = $userModel->fetchOne($id);
    
                // Where do I store this user object ???
            }
    
        }
    }
    
  3. The problem is: where do i store this User object? I think we shouldn't use sessions for this, since the goal of sessions is to persist data. There's no need for persistence though, since we re-fetch the data from the database on each request. Only the user ID must be persistent. Would storing the User object in Zend_Registry be an option here?


更改用户个人资料时,将重新认证作为其中一部分是否合适?毕竟,您需要确保用户确实是本人。这是一个很好的重认证和更新存储的机会。 - RockyFord
3个回答

1

我认为举例会是解释如何将新的身份验证详情写入Zend_Auth存储对象最好的方法:

$userDetails = array('foo' => 'bar');
$storage = new Zend_Auth_Storage_Session();
// set sorage for Zend_Auth
Zend_Auth::getInstance()->setStorage($storage);
// write data to the storage
Zend_Auth::getInstance()->getStorage()->write($userDetails);
// read data from storage
var_dump(Zend_Auth::getInstance()->getStorage()->read());
// edit user's data
$userDetails = array('foo' => 'bar', 'foo', 'bar');
// write new data to storage
Zend_Auth::getInstance()->getStorage()->write($userDetails);
// read new written data from storage
var_dump(Zend_Auth::getInstance()->getStorage()->read());

我认为这解释了如何设置Zend_Auth存储,并在以后更改它。


你刚刚描述了如何向默认的Zend_Auth会话存储机制中添加数据。我已经知道如何做了。通过将所有用户详细信息存储在会话中,只有当用户重新进行身份验证时,对这些详细信息的更改才会生效。 - Freek Vanraes
你已经编辑了问题。无论如何,为什么不将用户对象存储在会话中(可以作为数组),并且只在用户编辑详细信息时重写它,而不是在每个请求中获取用户数据?如果这个选项不适合您,您总是可以在User_Model中拥有一个名为“getCurrentUser”的方法,其中包含静态字段$user,并且当查询完成时始终从此方法获取用户数据。 - Bartosz Grzybowski

0
使用Zend_Session_Namespace来存储对象。它可以是临时的或永久的,取决于您的需求。 Zend_Auth已经在后台使用此机制作为默认存储机制,使用命名空间Zend_Auth
class Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $session = new Zend_Session_Namespace('user');//instantiate session namespace
        if ($auth->hasIdentity())
        {
            $id = $auth->getIdentity()->id;

            $userModel = new Model_User();

            $user = $userModel->fetchOne($id);

            $session->user = $user;//store the object can be recalled anywhere
        }
    }
}

当然,Zend_Registry 也可以正常工作,选择权永远在你手中。你甚至可能会发现将此功能构建到您的身份验证适配器中是合适的。


0

我认为在你的情况下使用Zend_Registry是可以的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接