cakephp 3.x更新用户数据

时间:2017-01-04 13:52:00

标签: php cakephp-3.0

我已经编写了一个基本的登录脚本,现在需要更新存储在auth组件中的数据,然后将其保存到数据库中,这是我到目前为止所做的;

public function login()
{
    if ($this->request->is('post')) {
        $user = $this->Auth->identify();
        if ($user) {                 
            $this->Auth->setUser($user);
            $this->Auth->user()->last_activity = date("Y-m-d");
            $this->Users->save($this->Auth->user());
            return $this->redirect($this->Auth->redirectUrl());
        }
        $this->Flash->error(__('Email or password is incorrect, please try again.'));
    }
}

我尝试了一些不同的版本但无法使用。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

更新cakephp3中的数据与cakephp2略有不同,请尝试以下方法:

public function login()
{
 if ($this->request->is('post')) {
    $user = $this->Auth->identify();
    if ($user) {                 
        $this->Auth->setUser($user);
         $userData = $this->Users->get($user['id']);
         $userData->last_activity = date("Y-m-d");
         if($this->Users->save($userData)){
            $user['last_activity'] = $userData->last_activity; // to update auth component
         }
         // echo $this->Auth->user('last_activity');
         return $this->redirect($this->Auth->redirectUrl());
    }
    $this->Flash->error(__('Email or password is incorrect, please try again.'));
 }
}

更新cakephp3中记录的另一种方法是:

$query = $this->Users->query();
 $query->update()
->set(['last_activity ' => date('Y-m-d')])
->where(['id' => $user['id']])
->execute();

但我不推荐这个,因为回调不会被解雇。

答案 1 :(得分:1)

在Cake3中,您可以利用afterIdentify事件。

AppController::initialize中,为事件添加一个侦听器:

EventManager::instance()->on('Auth.afterIdentify', [$this, 'afterIdentify']);

添加AppController::afterIdentify函数来处理事件:

public function afterIdentify(CakeEvent $cakeEvent, $data, $auth) {
    $users_table = TableRegistry::get('Users');

    $user = $users_table->get($data['id']);
    $user->last_activity = new Cake\I18n\FrozenTime();

    // If you ever need to do password rehashing, here's where it goes
    if ($this->Auth->authenticationProvider()->needsPasswordRehash()) {
        $user->password = $this->request->data('password');
    }

    $users_table->save($user);
}

现在,Auth->user()电话返回的数据应该始终是最新的,您无需付出额外的努力。