Cakephp:选择登录后要保存的数据
Posted
技术标签:
【中文标题】Cakephp:选择登录后要保存的数据【英文标题】:Cakephp: choose which data to save after login 【发布时间】:2012-10-24 13:22:47 【问题描述】:我不明白如何选择登录后保存哪些用户数据。我注意到我只能更改模型的递归性,但不能选择要使用的单个字段。
例如,通常Cakephp 会在会话中保存除密码以外的所有用户字段,甚至是我不需要且不想存储的数据。 如果我增加递归,Cakephp 会保存相关模型的所有字段。
Model find方法的“fields”参数有什么办法吗?
我知道登录后我可以恢复我错过的数据并将它们添加到会话中,合并到那些已经存储的数据,但我想避免进行其他查询并找到更优雅的解决方案(如果存在)。
谢谢。
【问题讨论】:
你用的是什么版本的 Cake? 【参考方案1】:从 Cake 2.2 开始,您可以将 contain
密钥添加到您的身份验证选项中以提取相关数据。由于contain
键接受fields
键,因此您可以限制那里的字段:
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form' => array(
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
如果您想更改用户模型搜索的字段,您可以扩展您正在使用的身份验证对象。通常 users 表包含的信息量很少,因此通常不需要这样做。
不过,我还是举个例子吧。我们将在这里使用 FormAuthenticate 对象,并使用 BaseAuthenticate 类中的大部分 _findUser
方法代码。这是 Cake 的身份验证系统用来识别用户的函数。
App::uses('FormAuthenticate', 'Controller/Component/Auth');
class MyFormAuthenticate extends FormAuthenticate
// overrides BaseAuthenticate::_findUser()
protected function _findUser($username, $password)
$userModel = $this->settings['userModel'];
list($plugin, $model) = pluginSplit($userModel);
$fields = $this->settings['fields'];
$conditions = array(
$model . '.' . $fields['username'] => $username,
$model . '.' . $fields['password'] => $this->_password($password),
);
if (!empty($this->settings['scope']))
$conditions = array_merge($conditions, $this->settings['scope']);
$result = ClassRegistry::init($userModel)->find('first', array(
// below is the only line added
'fields' => $this->settings['findFields'],
'conditions' => $conditions,
'recursive' => (int)$this->settings['recursive']
));
if (empty($result) || empty($result[$model]))
return false;
unset($result[$model][$fields['password']]);
return $result[$model];
然后使用该身份验证并通过我们的新设置:
public $components = array(
'Auth' => array(
'authenticate' => array(
'MyForm' => array(
'findFields' => array('username', 'email'),
'contain' => array(
'Profile' => array(
'fields' => array('name', 'birthdate')
)
)
)
)
)
);
【讨论】:
【参考方案2】:我只是在这个问题上花了一些时间,才发现在 Cake 2.6 中已经实现了一个 'userFields' 选项
在此处查看文档: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
【讨论】:
以上是关于Cakephp:选择登录后要保存的数据的主要内容,如果未能解决你的问题,请参考以下文章