質問
現在Save()が呼び出される前に、オブジェクトに追加されるさまざまなものを必要とするリチウムアプリケーションを開発しています。
理想的には、次のようなモデルクラス(他のモデルが伸びる基本モデル)に適用するフィルタを書くことができます。
Model::applyFilter('save', function($self, $params, $chain) {
// Logic here
});
.
これは可能ですか?もしそうならそれはブートストラップファイルになるべきですか?
解決
あなたが言っていることを誤解していない場合は、たとえば、保存前に 'created'または 'modified'の値を自動的に追加したいです。
これは私がそれをする方法です。
My 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を使用して、オーバーライドされたSave()メソッドを持つBaseModel
クラスを使用し、そのすべてのアプリケーションモデルを継承する。
他の方法は、ブートストラップファイル内の各モデルにフィルタを怠惰に適用されるでしょう。例えば:
Filters::apply('app\models\Documents', 'save', $timestamp);
Filters::apply('app\models\Queries', 'save', $timestamp);
Filters::apply('app\models\Projects', 'save', $timestamp);
.
$timestamp
Aクロージャー
*フィルタ継承は計画でもまだ
所属していません StackOverflow