【问题标题】:Lithium Generic Model Filter锂通用模型滤波器
【发布时间】:2012-03-08 16:19:17
【问题描述】:

我目前正在开发一个锂应用程序,它需要在调用 save() 之前向对象添加各种内容。

理想情况下,我可以编写一个过滤器以应用于 Model 类(其他模型扩展的基本模型),如下所示:

Model::applyFilter('save', function($self, $params, $chain) {
    // Logic here
});

这可能吗?如果是这样,它应该是一个引导文件吗?

【问题讨论】:

    标签: php filter aop lithium


    【解决方案1】:

    如果我没有误解您的意思,例如,您希望在保存之前自动将“创建”或“修改”的值添加到对象。

    我是这样做的。

    来自我的extensions/data/Model.php

    <?php
    namespace app\extensions\data;
    use lithium\security\Password;
    
    class Model extends \lithium\data\Model {
    
        public static function __init() {
            parent::__init();
    
            // {{{ Filters
            static::applyFilter('save', function($self, $params, $chain) {
                $date   = date('Y-m-d H:i:s', time());
                $schema = $self::schema();
    
                //do these things only if they don't exist (i.e.  on creation of object)
                if (!$params['entity']->exists()) {
    
                    //hash password
                    if (isset($params['data']['password'])) {
                        $params['data']['password'] = Password::hash($params['data']['password']);
                    }
    
                    //if 'created' doesn't already exist and is defined in the schema...
                    if (empty($params['date']['created']) && array_key_exists('created', $schema)) {
                        $params['data']['created'] = $date;
                    }
                }
    
                if (array_key_exists('modified', $schema)) {
                    $params['data']['modified'] = $date;
                }
                return $chain->next($self, $params, $chain);
            });
            // }}}
        }
    }
    
    ?>
    

    我也有一些密码哈希。您可以删除它而不影响任何功能。

    【讨论】:

      【解决方案2】:

      过滤器不支持继承*。

      您最好使用 OOP 并拥有一个 BaseModel 类,该类具有重写的 save() 方法,并且您的所有应用程序模型都从该类继承。

      另一种方法是在引导文件中懒惰地对每个模型应用过滤器。例如:

      Filters::apply('app\models\Documents', 'save', $timestamp);
      Filters::apply('app\models\Queries', 'save', $timestamp);
      Filters::apply('app\models\Projects', 'save', $timestamp);
      

      $timestamp 闭包

      *过滤器继承是planned但还不是implemented

      【讨论】:

        猜你喜欢
        • 2014-07-29
        • 2014-04-15
        • 1970-01-01
        • 2021-06-12
        • 2014-02-09
        • 1970-01-01
        • 2016-02-29
        • 2018-03-28
        • 2023-04-10
        相关资源
        最近更新 更多