I’m trying to write my first project in CakePHP2 (I used CakePHP1 before) and I have the following problem.
I have several models that require a custom validation rule for a field (personal numeric code). The validation rule is quite large so I don’t want to repeat the code in each model.
Instead, I thought about writing a component with a function that will receive a string as a parameter and validate it, and just calling that particular function from each model.
I read that components should be used in controllers, so maybe this is not the best way to do it?
What I’m trying to do is actually extend ModelValidator and add my own custom rules, but I have no idea if that is possible.
Thank you for you help.
I found an answer to my own question: Behaviors.
The CakePHP structure recomends that:
Components should be used in Controllers
Helpers should be used in Views
Behaviors should be used in Models
To define the behavior I did the following:
In the app/Model/Behavior/ValidateBehavior.php file:
In my model app/Model/User.php where I need to validate the data:
The good thing about Behaviors is that they seem to act like parent classes and they can also contain callback functions for beforeSave, beforeDelete, etc.
The model can call a function from the Behavior like a method of his own, which means behaviors can also be used in controllers: