我正在使用 CakePHP2.8,我想在模型之间共享多个自定义验证方法。
我CustomValidators.php
使用已知在模型中工作的自定义验证方法创建了一个助手类。这里的逻辑没有问题,这里只是为了说明。
<?php
App::uses('CakeLog', 'Utility');
class CustomValidators {
public function checkDateNotFuturePast($checks, $params)
{
$params += array(
'type' => 'past', //Date cannot be in the past
'current_date' => 'now', //Todays date
'include_current_date' => false //Allow current date to pass validation
);
CakeLog::write('error', print_r(json_encode([
'checks' => $checks,
'params' => $params,
]), true));
$date = array_values($checks)[0];
try {
$timezone = new DateTimeZone("UTC");
$input_date = new DateTime($date, $timezone);
$current_date = new DateTime($params['current_date'], $timezone);
} catch(Exception $e) {
return false;
}
switch ($params['type']) {
case 'future':
if($params['include_current_date']){
if($input_date->format('dmY') != $current_date->format('dmY')&&$input_date->format('U') > $current_date->format('U')) return false;
}else{
if($input_date->format('U') > $current_date->format('U')) return false;
}
break;
case 'past':
if($params['include_current_date']){
if($input_date->format('dmY') != $current_date->format('dmY')&&$input_date->format('U') <= $current_date->format('U')) return false;
}else{
if($input_date->format('U') < $current_date->format('U')) return false;
}
break;
}
return true;
}
public function checkNotOlderThan($check, $params)
{
CakeLog::write('error', 'CustomValidators::checkNotOlderThan');
$params += [
'current_date' => date('Y-m-d'),
];
CakeLog::write('error', print_r(json_encode([
'checks' => $checks,
'params' => $params,
]), true));
if (!isset($params['range'])) {
return false;
}
$date = array_values($check)[0];
try {
$current_date = new DateTime($params['current_date']);
$current_date->modify('-' . $params['range']);
$input_date = new DateTime($date);
} catch(Exception $e) {
return false;
}
if ($input_date >= $current_date) {
return true;
}
return false;
}
}
我将此文件包含在模型中JobCustomA
并将其实例化为beforeValidate
.
public function beforeValidate($options = [])
{
$CustomValidators = new CustomValidators();
我正在尝试JobCustomA
在其模型中进行所有验证,这将验证来自Job
.
在我的JobCustomA
模型中,我想在 上添加验证Job
,我这样做:
public function beforeValidate($options = [])
{
$CustomValidators = new CustomValidators();
$this->Job->validator()->add('deposit_paid', [
'not_future' => [
'rule' => [
'userDefined', $CustomValidators, 'checkDateNotFuturePast', [
'type' => 'future',
]
],
'message' => 'Deposit date can\'t be in the future',
],
'nottooold' => [
'rule' => [
'userDefined', $CustomValidators, 'checkNotOlderThan', [
'current_date' => date('Y-m-d'),
'range' => '120 days',
],
],
'message' => 'Deposit date can\'t have been paid more than 120 days ago',
],
]);
// ...
}
但是,它似乎不会使用这些自定义验证方法,我不知道如何解决这个问题。我需要能够在许多类之间重用自定义验证方法,而无需在每个模型中复制它们。
TL;DR:在验证器添加中使用userDefined
角色不起作用,需要在多个模型之间重用许多自定义验证方法。
谢谢