Database Cakephp:如何在会话中读取用户数据?
我想从用户模型中收集用户的最新信息,并将其存储在会话中 所以我要这么做 //渲染前 函数beforeRender(){ } 它在用户模型中运行良好,直到am 当我转到页面时,它会给我一个错误,因为用户->读取不起作用,因为该模型没有附加在那里 最好的解决方案是什么Database Cakephp:如何在会话中读取用户数据?,database,session,cakephp,cakephp-1.3,Database,Session,Cakephp,Cakephp 1.3,我想从用户模型中收集用户的最新信息,并将其存储在会话中 所以我要这么做 //渲染前 函数beforeRender(){ } 它在用户模型中运行良好,直到am 当我转到页面时,它会给我一个错误,因为用户->读取不起作用,因为该模型没有附加在那里 最好的解决方案是什么 我想在网站的每一页上的Loggedin用户的最新信息 会话中最新且未授权的用户,因为-当我编辑配置文件内容(如名称或照片)时。它仍然引用用户登录时存储的旧数据 它必须显示在每个页面上,就像顶部的Stackoverflow用户信息一样
/app/app\u controller.php
李>
beforeRender
函数$uses
请参阅。您可以尝试在beforeRender中加载模型,如下所示:
$this->load('User')
,这将在每个控制器中为您加载模型。
其他建议似乎增加了应用程序的开销(通过加载和查询每个请求的用户模型)。您是否考虑过在用户模型发生更新时简单地更新过时的会话数据
<?php
class UsersController extends AppController {
public function edit() {
$userId = $this->Session->read('Auth.User.id');
// populate form
if (!$this->data) {
$this->data = $this->User->read($userId, null);
return;
}
// update user
$saved = $this->User->save($this->data);
if ($saved) {
$user = $this->User->read(null, $this->User->id);
$this->Session->write('Auth.User', $user['User']); // update session
$this->Session->setFlash('Account details have been updated');
return $this->redirect(array('action' => 'profile'));
}
$this->Session->setFlash('Please correct the validation errors below');
}
}
?>
这意味着您需要的数据将在每个请求中收集,而无需任何其他查询(如果使用
php
或cake
会话存储,则从磁盘收集,如果使用数据库
存储,则在单个会话查询中收集)。。除了美元,我什么都做了。现在工作。谢谢这是正确的方法吗?是的,正如文档中所说,“这是创建所有控制器通用的代码的理想场所。”但是您可以尝试在Fileter之前而不是在PreRender之前创建代码。请参阅文档:在beforeFilter中,您可以加载所有安全设置,在所有控制器中,您将拥有$this->Auth->user(),我更倾向于使用bindModel()
而不是$uses
<?php
class UsersController extends AppController {
public function edit() {
$userId = $this->Session->read('Auth.User.id');
// populate form
if (!$this->data) {
$this->data = $this->User->read($userId, null);
return;
}
// update user
$saved = $this->User->save($this->data);
if ($saved) {
$user = $this->User->read(null, $this->User->id);
$this->Session->write('Auth.User', $user['User']); // update session
$this->Session->setFlash('Account details have been updated');
return $this->redirect(array('action' => 'profile'));
}
$this->Session->setFlash('Please correct the validation errors below');
}
}
?>