在CakePHP应用程序中是否有一种首选方式来存储用户的首选项?


Is there a preferred way to store a user's preferences in a CakePHP application?

我想知道是否有一种被广泛接受的方式来在CakePHP应用程序中存储用户的首选项。例如,我能想到的一些方法是:

  1. 在用户模型中设置单独的字段。
  2. 有一个带有键和值字段的首选项表。
  3. 有一个参数表,每个用户有一个条目,参数作为字段。(类似于第一个,我想)

是否有一种方法可以更好地用于可能改变或扩展的应用程序(即可以考虑添加或删除首选项的方法)?

你可能想看看CakeDC的Utils插件中的KeyvalueBehavior作为起点。

将插件提取到Plugin/Utils/,并创建名为preferences的数据库表,其中包含以下字段:user_id, field, value

<?php
class Preference extends AppModel {
    $actsAs = array('Utils.Keyvalue');
}

然后您可以像这样保存和检索首选项(假设User hasMany Preferences):

$this->User->Preference->saveSection($this->Auth->user('id'), array(
    'Preference' => array(
        'dob' => 'mm/dd/yyyy',
        'gender' => 'm|f|n',
        'url' => 'http://www.example.com',
    )
), 'Profile');
$this->User->Preference->getSection($this->Auth->user('id'), 'Profile');

如果你想在web界面上添加或删除偏好(不改变数据库模式),那么你需要第二个选项(EAV模型)。缺点是,查询将会非常复杂。

但如果偏好变化很少,则执行第三个。

您还可以考虑在Cookie中存储依赖于用户的非关键信息。如果使用寿命长,这就足够了。