2012-03-08 105 views
3

我目前正在開發一個鋰應用程序,它需要在調用save()之前將各種東西添加到對象中。鋰通用型濾波器

理想我想能寫一個過濾器適用於Model類(其他車型擴展了基礎模型),如下列:

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

這可能嗎?如果是的話,它應該是一個引導文件?

回答

5

如果我沒有誤解你的意思,你想,例如,在保存之前自動將「創建」或「修改」的值添加到對象。

下面是我如何做到這一點。

從我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); 
     }); 
     // }}} 
    } 
} 

?> 

我有一些密碼散列有作爲。您可以刪除它,而不影響任何功能。

4

過濾器不支持繼承*。

您最好使用OOP並使用覆蓋save()方法的BaseModel類,並從中繼承所有應用程序模型。

另一種方式是在引導文件中將每個模型的過濾器延遲應用。例如:

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

$timestamp封閉

*過濾器繼承planned但尚未implemented