I’m creating a large PHP project and I’ve a trivial doubt about how to proceed.
Assume we got a class books, in this class I’ve the method ReturnInfo:
function ReturnInfo($id) {
if( is_numeric($id) ) {
$query = "SELECT * FROM books WHERE id='" . $id . "' LIMIT 1;";
if( $row = $this->DBDrive->ExecuteQuery($query, $FetchResults=TRUE) ) {
return $row;
} else {
return FALSE;
}
} else {
throw new Exception('Books - ReturnInfo - id not valid.');
}
}
Then i have another method PrintInfo
function PrintInfo($id) {
print_r( $this->ReturnInfo($id) );
}
Obviously the code sample are just for example and not actual production code.
In the second method should I check (again) if id is numeric ? Or can I skip it because is already taken care in the first method and if it’s not an exception will be thrown?
Till now I always wrote code with redundant checks (no matter if already checked elsewhere i’ll check it also here)
Is there a best practice? Is just common sense?
Thank you in advance for your kind replies.
Well, ask yourself what you gain by checking in every layer. Is it more security? No, since the function which uses the value for something, which is the only one being vulnerable, does the checking itself.
The only advantage it has is that you can stop invalid values earlier, which executes less code. It doesn’t have to go all the way down and back up before you know the value is invalid. This may or may not be a real advantage.
It does create problems though: you have more code. Your code is not DRY anymore. If you change the definition of what makes a “valid” value, you have to change the checks all over the place. Those are much bigger problems.
I’d approach the problem this way: your core business model does the in-detail checking, it is ultimately responsible for making sure the value is valid, and it is the only one doing something “dangerous” with this value. The outer layers (controllers, views) merely pass the value along. With one exception: they may do “rough” data validation. Say your model expects a phone number with specific formatting. You should check this specific rule inside the model. In the view/controller layer you may roughly validate the value as being at least somewhat numeric though. Say, you have a Javascript check. This blocks obviously wrong values from bothering your core app, while still giving you the flexibility to tweak the core validation rule in just one place.