[英]Lithium Generic Model Filter
I am currently developing a Lithium application which requires various things to be added to an object before save() is called. 我目前正在开发一个Lithium应用程序,它需要在调用save()之前向对象添加各种内容。
Ideally I would be able to write a filter to apply to the Model class (the base model that other models extends) such as the following: 理想情况下,我可以编写一个过滤器来应用于Model类(其他模型扩展的基本模型),如下所示:
Model::applyFilter('save', function($self, $params, $chain) {
// Logic here
});
Is this possible? 这可能吗? If so should it be a bootstrapped file? 如果是这样,它应该是一个自举文件?
If I'm not misunderstanding what you're saying, you want to, for example, automatically add a value for 'created' or 'modified' to an object before save. 如果我没有误解你所说的内容,你想要在保存之前自动为对象添加“已创建”或“已修改”的值。
Here's how I do that. 我就是这样做的。
From my extensions/data/Model.php
来自我的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);
});
// }}}
}
}
?>
I have some password hashing there as well. 我也有一些密码哈希。 You can remove that without affecting any functionality. 您可以删除它而不影响任何功能。
Filters don't support inheritance*. 过滤器不支持继承*。
You'd better use OOP and have a BaseModel
class with an overridden save() method, and from which all your app models inherits. 你最好使用OOP并使用一个带有重写的save()方法的BaseModel
类,并从中继承所有的app模型。
An other way would be lazily apply filters to each model, in a bootstrapped file. 另一种方法是在引导文件中懒洋洋地将过滤器应用于每个模型。 For example: 例如:
Filters::apply('app\models\Documents', 'save', $timestamp);
Filters::apply('app\models\Queries', 'save', $timestamp);
Filters::apply('app\models\Projects', 'save', $timestamp);
with $timestamp
a closure 使用$timestamp
一个闭包
* filters inheritance is planned but not yet implemented *过滤器继承已计划但尚未实施
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.