CakePHP 4 - Authentication插件:如何获取当前用户名?解决更新用户资料后用户名未实时更新的问题
我来帮你搞定这两个问题——先确认正确的用户名获取方式,再解决更新后不实时显示的问题:
一、CakePHP 4中使用Authentication插件获取当前用户名的正确方式
你现在写的代码其实是完全没问题的:
$user = $this->request->getAttribute('identity'); $name = $user->first_name ?? '';
另外还有一种更直观的方式,通过Authentication组件直接获取身份信息(前提是你的控制器已经加载了Authentication组件,一般AppController里会全局加载):
// 如果控制器没加载组件,先加这行(AppController里加一次就行) $this->loadComponent('Authentication.Authentication'); // 获取当前用户身份 $user = $this->Authentication->getIdentity(); $name = $user->first_name ?? '';
两种方式本质是等价的,getIdentity()内部也是从request的attribute里读取数据,选你觉得顺手的用就行。
二、解决更新资料后用户名不实时更新的问题
这个问题的核心原因很简单:用户登录时,身份信息已经被存在Session会话里了,你更新数据库后,Session里的旧数据并没有同步更新,所以必须登出再登录才能拿到新数据。
解决方法就是在更新用户资料并保存成功后,把最新的用户数据重新写入Session的身份信息中。举个例子,假设你在UsersController的edit方法里处理更新:
public function edit($id = null) { // 获取要更新的用户(如果是当前用户自己的资料,也可以用$this->Authentication->getIdentity()) $user = $this->Users->get($id); if ($this->request->is(['patch', 'post', 'put'])) { $user = $this->Users->patchEntity($user, $this->request->getData()); if ($this->Users->save($user)) { $this->Flash->success(__('用户资料更新成功')); // 关键一步:把更新后的用户数据同步到Session中 $this->Authentication->setIdentity($user); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('更新失败,请重试')); } $this->set(compact('user')); }
加了$this->Authentication->setIdentity($user)这行之后,Session里的身份信息就会被替换成最新的用户数据,后续再获取first_name时就能拿到更新后的值,不用再登出登录了。
如果是更新当前登录用户自己的资料,建议直接用$user = $this->Authentication->getIdentity()来获取用户实体,这样更安全,避免误操作其他用户的数据。
内容的提问来源于stack exchange,提问作者Kiruaaa
相关产品推荐
相关产品推荐

