题
我目前正在开发锂应用程序,该应用程序需要在调用save()之前要在对象添加到对象中的各种事物。
理想情况下,我能够编写一个过滤器,以应用于模型类(其他模型扩展的基础模型),例如以下:
Model::applyFilter('save', function($self, $params, $chain) {
// Logic here
});
.
这可能吗?如果是这样,它应该是一个引导文件?
解决方案
如果我没有误解你所说的话,你想要在保存之前自动添加“创建”或“修改”或“修改”的值。
这是我的方式。
从我的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);
});
// }}}
}
}
?>
.
我还有一些密码散列。您可以在不影响任何功能的情况下删除。
其他提示
过滤器不支持继承*。
您最好使用OOP并具有具有覆盖保存()方法的BaseModel
类,以及您的所有应用程序模型继承的所有应用程序。
其他方式将懒惰地将过滤器应用于每个模型,在引导文件中。例如:
Filters::apply('app\models\Documents', 'save', $timestamp);
Filters::apply('app\models\Queries', 'save', $timestamp);
Filters::apply('app\models\Projects', 'save', $timestamp);
.
与$timestamp
封闭
不隶属于 StackOverflow