How do we handle validation when using implicit setters and getters? I imagine when using explicit getters and setters, we would do something like:
public void function setFirstName() {
if (! len(arguments.firstName)) {
//throw some error/add an error to an error container
} else {
variables.firstName = arguments.firstName;
}
}
If we use implicit getters and setters, we can define validation rules within the CFC itself, such as:
/**
* @validate string
* @validatepar开发者_运维技巧ams {minLength=2, maxLength=40}
*/
property String firstName;
My questions are:
- Would validation logic be in the CFC itself, or from the caller?
- How do we trap errors and return them to the user for feedback? I can think of using try/catch, but should this be in the controller or the Model?
I'm a newbie to OOP and I've relied on CFWheels to do all of this for me. I'd like to learn how this functionality is handled in the absence of a framework, or if I were using Hibernate, for example.
When I was in college doing Java, validation was usually done in setter. However, after working in web dev for a while, I noticed that it's generally not a good idea because you generally want to construct a batch of error messages and return to the user. Therefore, a validate()
method in the object, or a validateX()
method at the Service layer that returns a collection of errors would be more suitable.
Having said that, beside ValidateThis, there's also http://hyrule.riaforge.org/ if you are running CF9.
Personally, I do not think validation should be done inside the object that is being validated. I prefer an external process, such as ValidateThis http://www.validatethis.org/
It is a pretty powerful and flexible 'framework' (for lack of a beter word) for validating objects. it allows you to validate properties that are simple values, complex values (structs, arrays) and other objects.
精彩评论