【发布时间】:2012-03-20 11:05:49
【问题描述】:
我正在使用 CakePHP 2.0 的集成 Auth 组件。 我有以下表格:
- 用户
- 组
- 个人资料
我的模型关系如下:
User belongsTo Group
User hasMany Profiles
登录网站时,我注意到 Auth 会话仅包含用户表信息,但我也需要登录用户的组和配置文件表信息。
有什么方法可以用 Auth 组件做到这一点吗?
【问题讨论】:
标签: cakephp cakephp-2.0
我正在使用 CakePHP 2.0 的集成 Auth 组件。 我有以下表格:
- 用户
- 组
- 个人资料
我的模型关系如下:
User belongsTo Group
User hasMany Profiles
登录网站时,我注意到 Auth 会话仅包含用户表信息,但我也需要登录用户的组和配置文件表信息。
有什么方法可以用 Auth 组件做到这一点吗?
【问题讨论】:
标签: cakephp cakephp-2.0
AuthComponent 无法做到这一点,因为它处理会话密钥的方式。但是,您可以自己将其保存到会话中。
这样做的唯一方法是在用户登录时添加到会话中:
function login() {
if ($this->Auth->login($this->data)) {
$this->User->id = $this->Auth->user('id');
$this->User->contain(array('Profile', 'Group'));
$this->Session->write('User', $this->User->read());
}
}
然后在您的beforeFilter() 中的AppController 中,保存一个变量供控制器访问:
function beforeFilter() {
$this->activeUser = $this->Session->read('User');
}
// and allow the views to have access to user data
function beforeRender() {
$this->set('activeUser', $this->activeUser);
}
更新:从 CakePHP 2.2 (announced here) 开始,AuthComponent 现在接受 'contain' 键以在会话中存储额外信息。
【讨论】:
据我所知,Auth 组件仅缓存来自用户模型的数据。您可以使用该信息从其他模型中检索所需的数据,例如在您的控制器中使用:
$group_data = $this->Group->findById($this->Auth->user('group_id'));
或者
$profile_data = $this->Profile->findByUserId($this->Auth->user('id'));
但我认为你不能直接从 Auth 组件中获取它,因为它不会缓存相关的模型数据。
【讨论】:
两种方式:
1) 扩展 FormAuthenticate 类(参见 /Controller/Component/Auth)或任何您用来登录并覆盖 _findUser() 方法并告诉 Auth 组件使用此授权类的东西。看看这个页面如何做所有这些http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
2) 只需在模型中实现一个方法,该方法将获取您想要的所有数据并在控制器的登录方法中调用它并将数据写入会话。 IMO 使用这种方法很方便,因为有时您无论如何都需要刷新会话数据。
因为您对另一个答案的评论:
您必须在模型中编写一个方法和一些代码来返回数据。 CakePHP 无法读取您的想法和没有代码的数据库。无论您要使用这两种建议方式中的哪一种,您都必须编写代码。
【讨论】: