drey/prefs

存储和检索用户偏好

1.0.2 2016-03-19 17:38 UTC

This package is not auto-updated.

Last update: 2024-09-25 12:27:45 UTC


README

存储和检索用户偏好。

  1. 根据上一次提交的默认值记住表单(例如,根据上次搜索重复日期限制或下拉列表中的帐户选择)。
  2. 自定义网站的外观和感觉。
  3. 等等。

用法

文件系统中的数据库

    use drey\Prefs\Factory;

    # Obtain a Prefs object
    # with file system storage and username
    $prefs = Factory::fileSystem('/path/to/directory','bob') 

    # set preference "color" for current user (bob)
    $prefs->set('color','red');
    
    # get color preference of current user
    $color = $prefs->get('color');
    
    # $color is set to 'red'

RDMB 中的数据库

使用pdo工厂相应地更改DB介质。

    use drey\Prefs\Factory;

    # obtain a PDO object
    $pdo = myConnect();

    # Obtain a Prefs object
    # with RDBM storage and username
    $prefs = Factory::pdo($pdo,'bob') 
 
    # set preference "color" for current user (bob)
    $prefs->set('color','red');
    
    # get color preference of current user
    $color = $prefs->get('color');
    
    # $color is set to 'red'

MySQL的表结构应该是(请参阅目录 sql/

        CREATE TABLE `prefs`  (
          `name` varchar(255) NOT NULL,
          `value` varchar(255) NOT NULL,
          `username` varchar(32) NOT NULL,
          PRIMARY KEY (`name`,`username`),
          KEY (`username`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

默认值

如果找不到键,可以提供默认值。

    $bird = $prefs->get('bird','eagle');
    
    # $bird is set to 'eagle' if key 'bird' not found

指定其他用户的偏好

分配/读取其他用户的偏好

    $prefs->set('fruit','lemmon','alice');
    # ...
    $prefs->get('fruit','pear','alice')

全局偏好

可以使用全局用户名来处理所有用户的偏好。所有用户都必须同意全局用户名(例如 '*')。

    # one user
    $prefs->set('closing_date',$form->closing_date,'*');

    (...)

    # other users
    $closing_date = $prefs->get('closing_date',date('Y-m-d'),'*');
   
 

填充表单字段

如果我们的模型中的字段没有值并且我们正在创建一个新记录,则用默认值填充字段。

    # before showing the form get the last value entered
    if ($model->isNewRecord && !$model->date) {
        $model->date = $prefs->get('invoice_date',date('Y-m-d'));
    }

    # after post, update value entered
    if (post) {
        $prefs->set('invoice_date',$model->date);
    }

使用Composer安装

该软件包作为 drey/prefs 存在于Packagist仓库中。

请参阅 drey/prefs