我该怎么办模特会话? CakePHP 3.x

前端之家收集整理的这篇文章主要介绍了我该怎么办模特会话? CakePHP 3.x前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
CakePHP 3.x

我想做我的验证码自定义验证.但我无法访问会话.

$validator->notEmpty('securityCode',__('not empty message'))
    ->add('securityCode','custom',['rule' => function ($value,$context) use ($extra) {
            if($this->request->Session()->read('captcha') != $value) {
                return false;
            }
            return true;
        },'message' => 'error security code']);
 return $validator;

或者我的自定义验证功能可以提供自定义参数吗?

public function validationLogin(Validator $validator,$customParameter)
{ //bla bla }

我用的是:http://book.cakephp.org/3.0/en/core-libraries/validation.html#custom-validation-rules

您可以将Session数据作为验证函数的参数传递
// In Controller
$sessionData = $this->request->Session()->read('captcha');
$validator = $this->{YourModel}->validationLogin(new Validator(),$sessionData);

$errors = $validator->errors($this->request->data());
if (!empty($errors)) {
    // Captcha validation Failed
}


// In Model
public function validationLogin(Validator $validator,$sessionData)
{
    $validator
        ->notEmpty('securityCode',__('not empty message'))
        ->add('securityCode',[
            'rule' => function ($value,$context) use ($sessionData) {
                if ($sessionData != $value){
                    return false;
                }
                return true;
            },'message' => 'error securty code'
        ]);

        return $validator;
}

编辑:你可以从模型访问会话,但这不是一个好习惯,你最好避免它.而是将其从控制器传递,如上例所示

// In model
use Cake\Network\Session;
$session = new Session();
$sessionData = $session->read('captcha');
原文链接:https://www.f2er.com/php/137937.html

猜你在找的PHP相关文章