cakephp 3.x更新用户数据 [英] cakephp 3.x updating user data
问题描述
我已经写了一个基本的登录脚本,现在需要更新存储在auth组件中的数据,然后将其保存到数据库中,这是我到目前为止所要做的;
I have written a basic login script and now need to update the data stored in the auth component and then save it to the database, this is what i have so far;
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.'));
}
}
我尝试了几种不同的变体,但没有任何效果.有什么想法吗?
I've tried a few different variations but can't get any to work. Any ideas?
推荐答案
在Cake3中,您可以利用 afterIdentify
事件.
In Cake3, you can take advantage of the afterIdentify
event.
在 AppController :: initialize
中,为事件添加一个侦听器:
In AppController::initialize
, add a listener for the event:
\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()
调用返回的数据应该始终是最新的,而无需您付出任何额外的努力.
Now, the data returned by the Auth->user()
call should always be up-to-date without any extra effort on your part.
这篇关于cakephp 3.x更新用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!