[英]cakephp 3.x updating user data
我已经编写了一个基本的登录脚本,现在需要更新存储在 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.'));
}
}
我尝试了几种不同的变体,但都无法正常工作。 有任何想法吗?
在 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();
但我不推荐这个,因为不会触发回调。
在 Cake3 中,您可以利用afterIdentify
事件。
在AppController::initialize
,为事件添加一个监听器:
\Cake\Event\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()
调用返回的数据应该始终是最新的,您无需付出任何额外的努力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.