私は私が拡張するベースモデルを持っています。その中で、2つの検証フィルターを定義しました。1つはレコードが一意であるかどうかをチェックし、もう1つはレコードが存在するかどうかをチェックします。これらは、一方の戻り値が他方の逆になることを除いて、まったく同じように機能します。
したがって、同じコードを2回記述して、異なる値を返すだけでは正しくありません。あるカスタムバリデーターを別のカスタムバリデーターから呼び出す方法を知りたいのですが。
unique
バリデーターのコードは次のとおりです。
<?php
Validator::add('unique', function($value, $rule, $options) {
$model = $options['model'];
$primary = $model::meta('key');
foreach ($options['conditions'] as $field => $check) {
if (!is_numeric($field)) {
if (is_array($check)) {
/**
* array(
* 'exists',
* 'message' => 'You are too old.',
* 'conditions' => array(
*
* 'Users.age' => array('>' => '18')
* )
* )
*/
$conditions[$field] = $check;
}
} else {
/**
* Regular lithium conditions array:
* array(
* 'exists',
* 'message' => 'This email already exists.',
* 'conditions' => array(
* 'Users.email' //no key ($field) defined
* )
* )
*/
$conditions[$check] = $value;
}
}
/**
* Checking to see if the entity exists.
* If it exists, record exists.
* If record exists, we make sure the record is not checked
* against itself by matching with the primary key.
*/
if (isset($options['values'][$primary])) {
//primary key value exists so it's probably an update
$conditions[$primary] = array('!=' => $options['values'][$primary]);
}
$exists = $model::count($conditions);
return ($exists) ? false : true;
});
?>
exists
このように動作するはずです:
<?php
Validator::add('exists', function($value, $rule, $options) {
$model = $options['model'];
return !$model::unique($value, $rule, $options);
});
?>
しかし、明らかに、それはそのように行うことはできません。検証関数を無名関数として定義し、それを変数に割り当てて、クロージャーの代わりにそれを渡す必要がありますか?unique
または、内部から呼び出す方法はありますexists
か?