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

时间:2015-04-23 11:14:02

标签: session model cakephp-3.0

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

2 个答案:

答案 0 :(得分:10)

您可以像这样传递会话数据作为验证功能的参数

// 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', 'custom', [
            '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');

答案 1 :(得分:4)

对于CakePHP 3 :在Model类的顶部添加

use Cake\Network\Session;

并且您想要访问会话时添加

$this->session = new Session();
$messages = $this->session->read('captcha'); // Example for the default flash messages

要在模型中设置flash消息,请使用

$this->session = new Session();
$messages      = $this->session->read('Flash.flash');
$messages[]    = ['message' => 'YOUR FLASH MESSAGE', 'key' => 'flash', 'element' => 'Flash/default', 'params' => []];
$this->session->write('Flash.flash', $messages);