Confusing Validation vs. Application Rules in CakePHP3

蓝咒 提交于 2019-12-03 13:09:55

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

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!