Validation vs. Application Rules In CakePHP

|
| By Webner

CakePHP uses a two-layered approach to validation:

1. Validation
It determines basic validity. It ensures that the data types, size, and format of data are correct. When we call newEntity() or patchEntity() methods, validations are triggered. For example, checking if an email address is valid.

Some of Built-in Validation methods:

$validator = new Validator();

a. $validator->requirePresence() : It enforces that a field must be present in data array.
b. $validator->notEmpty() : It determines that the specified field cannot contain a non-empty value.
c. $validator->lengthBetween() : Add a rule that ensures a string length is within a range.
d. $validator->add() : Adds a new rule to a field’s rule set.

2. Application Rules
It checks the stateful properties of your entities. It commonly deals with the database to check data is correct or not. By using application rules, you can work with the data of an entity that is stored in the database. So that you will have full permission to access the current state of an object.

For example, if you want to check an email address is unique or you can not withdraw money more than your account balance.

$rules = RulesChecker;

a. $rules->isUnique(): It is used to check the uniqueness of a data which is stored into the database. This is useful for enforcing unique constraint checks.
b. $rules->existsIn(): This rule returns the callable object which is used to check the value of an entity whether it is present in another table as a primary key or not.
c. $rules->validCount(): This rule is used to check the number of related records.

NOTE: When we directly set properties of our entities, validation will not get triggered because validation methods only work for newEntity() and patchEntity() methods.

For example:

$user->email = 'email invalid!!';
$usersTable->save($user); 

In the above example , the entity will be saved without checking email is valid or not. In this case, incorrect data will be saved into the database.

Now, we will use application rules method to determine the validity of data. Application rules will be checked when save() or delete() methods are called. We will define this rule as below:

public function buildRules(RulesChecker $rules)
{    		             
 $rules->add($rules->isUnique(['email']));
 return $rules;
}

Now when we call the save() function to save the above entity, the save() function returns false and will not be allowed to save the data into database.

Leave a Reply

Your email address will not be published. Required fields are marked *