本文介绍了CakePHP3中令人困惑的验证与应用程序规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于验证的多个问题可能属于同一问题,因为它们都满足了CakePHP 3中的新验证概念。

Multiple questions about validation which may belong together, because they are all kind of adressing the new validation concept in CakePHP 3.

我已经阅读了以下章节(,,),但老实说,我不会不了解如何正确地做到这一点。我也知道,目前在。

I have read the chapters (1, 2, 3) in the cookbook multiple times but honestly I don't understand how to do it the right way. I also know there is currently a issue/discussion at GitHub about the Validation in CakePHP3 which may address the same topic.

触发验证错误,例如与patchEntity。因此,我认为最好在执行保存操作之前始终检查/显示错误:

Validation errors are triggered e.g. with patchEntity. So I would think it is better to ALWAYS check/display errors BEFORE doing the save action:

// src/Controller/UsersController.php
public function add() {
  $user = $this->Users->newEntity();
  if ($this->request->is('post')) {
    $user = $this->Users->patchEntity($user, $this->request->data, ['validate' => 'default'] );
    if ( $user->errors() ) {
      $this->Flash->error('There was a Entity validation error.');
    } else {
      // Optional: Manipulate Entity here, e.g. add some automatic values
      // Be aware: Entity content will not be validated again by default
      if ( $this->Users->save($user) ) {
        $this->Flash->succeed('Saved successfully.');
        return $this->redirect(['controller' => 'Users', 'action' => 'index']);
      } else {
        $this->Flash->error('Not saved - ApplicationRule validation error.');
      }
    }
  }
  $this->set('user', $user);
}

为什么菜谱教程不使用 $用户->错误()之前保存数据?据我了解,如果已经存在验证错误,则不需要调用保存吗?另一种方法是结合错误检查和保存操作:

Why do the cookbook tutorials not make use of $user->errors() before saving data? As far as I understand it save doesn't need to be called if there was a validation error already?! Another way would be to combine the error-check and save action:

if ( !$user->errors() && $this->Users->save($user) ) {
  $this->Flash->succeed('Saved successfully.');
  return $this->redirect(['controller' => 'Users', 'action' => 'index']);
} else {
  $this->Flash->error('There was a validation OR ApplicationRule error.');
}

您在使用吗?我应该使用它吗?否则,为什么不呢?

Are you using this? Should I use it? Or if not, why not?

即使我不使用 $ user-> errors()在控制器中,就像所有食谱示例一样?我以为保存不会检查实体验证?!

Why is CakePHP showing the validation errors even if I do NOT use $user->errors() in the controller, like in all the cookbook examples? I thought save will NOT check the entity validation?!

示例:isUnique

根据确保电子邮件的唯一性是应用程序规则的用例。

According to the cookbook "Ensuring email uniqueness" is a use case for application rules.

// src/Model/Table/UsersTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;
// Application Rules
public function buildRules(RulesChecker $rules) {
  $rules->add($rules->isUnique(['email'], 'This email is already in use'));
  return $rules;
}

仅通过 save -在控制器中调用。但是也可以在验证中检查唯一性。为什么最好不这样做呢?

The error would only be triggered with a save-call in the controller. But it is also possible to check uniqueness in the validation. Why is it better to NOT do it this way?

// src/Model/Table/UserTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
public function validationDefault(Validator $validator) {
  $validator
    ->add('email', [
      'unique' => [
        'rule' => 'validateUnique',
        'provider' => 'table',
        'message' => 'This email is already in use'
        ],
      ])
  return $validator;
}

如果我可以在验证中添加ApplicationRule,为什么/应该使用

If I can add the ApplicationRule in the Validation, why would/should I use ApplicationRules at all?

我应如何在仅应将规则应用于特定操作(并非所有创建/更新调用)的情况下在ApplicationRule中定义?

How can I define in the ApplicationRule WHEN the Rule should be applied only in a specific action (not all create/update calls)?

当在 patchEntity -call之后操纵实体时,我也看不到或理解两个分离的验证状态的好处

I also don't see or understand the benefit of the two separated validation states when the entity is manipulated after the patchEntity-call.

如果我将某些值自动添加到实体中,我想确保在将值保存到数据库之前所有值仍然有效(如CakePHP2中一样)。 。因此,我想总是 ?!

In case I add some values automatically to the entity, I want to be sure that the values are all still valid before saving them to the database (as in CakePHP2). So I would guess it's better/nessecary to ALWAYS Using Validation as Application Rules?!

您如何处理此问题一般?

How are you dealing with this in general? Are there other examples available to show/demonstrate the benefit and some use cases of the Validation vs. ApplicationRules?

推荐答案

我认为您的其他示例可以用来展示/演示Validation vs. ApplicationRules的好处和一些用例吗?造成混乱的主要原因是,您不知道 save()不会保存已存在错误的实体。例如:

I think your main source of confusion is that you don't know that save() will not save an entity if it contains errors already. For example:

$entity = $users->newEntity(['email' => 'not an email']);
$users->save($entity); // Returns false

返回false的原因是 save() 在进行实际保存过程之前,先读取 $ entity-> errors()结果。因此,不需要像调用手册中的示例那样在调用 save()之前手动检查错误。

The reason it will return false is because save() reads the $entity->errors() result before proceeding with the actual saving process. It is, then, unneeded to check for errors manually before calling save(), just as the examples in the manual show.

电子邮件唯一性示例有些棘手,因为您要同时检查面向用户的表单(面向验证的对象)和应用程序规则。

The email uniqueness example is kind of tricky, because it is something that you want to check both for user facing forms (what validation is targeted for) and in application rules.

重要的是要记住, Validation (如 validation *()方法中的)是用于向人们反馈他们所提供的数据。您想在保存过程开始之前以表格的形式显示所有错误(包括嵌套属性的错误)。

It is important to remember that Validation, as in the validation*() methods, is meant for giving feedback to humans about the data they are providing. You would like to present all errors in a form (including errors for nested properties) before the saving process start.

由于验证在数据库事务中很少发生,实际上并不能保证在验证和保存电子邮件之间仍然是唯一的。这是应用程序规则试图解决的事情之一:应用程序规则与其余保存过程在同一事务中运行,因此在那里进行的任何检查都将具有一致性保证。

Since Validation rarely happens inside a database transaction, there is no actual guarantee that between validation and saving the email would still be unique. This is one of the things application rules is trying to solve: Application rules do run in the same transaction as the rest of the saving process, so any checks donde there will have a consistency guarantee.

应用程序规则解决的另一个问题是它们可以处理已经在实体上设置的数据,因此您可以完全访问对象的当前状态。在修补实体或创建新实体时,这是不可能的,因为任何传递的数据都可能不一致。

Another problem application rules solve is that they can work on data that has already been set on the entity, hence you have full access to the current state of an object. That is not possible when patching an entity or when creating a new one, since any passed data is potentially inconsistent.

这篇关于CakePHP3中令人困惑的验证与应用程序规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:44