KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've learned that there are often many ways to solve one programming problem, each approach typically having its own benefits and negative side affects. What I'm trying to determine today is the best way to do model validation in PHP. Using the example of a person, I've outlined four different approaches I've used in the past, each including the classes and a usage example, as well as what I like and dislike about each approach. My question here is this: Which approach do you feel is best? Or do you have a better approach? Approach #1: Validation using setter methods in model class The good Simple, only one class By throwing exceptions, the class can never be in an invalid state (except for business logic, ie. death comes before birth) Don't have to remember to call a any validation methods The bad Can only return 1 error (via Exception ) Requires the use of exceptions, and catching them, even if the errors are not very exceptional Can only act upon one paramater since other paramaters may not be set yet (no way to compare birth_date and death_date ) Model class can be long due to lots of validation class Person { public $name; public $birth_date; public $death_date; public function set_name($name) { if (!is_string($name)) { throw new Exception('Not a string.'); } $this->name = $name; } public function set_birth_date($birth_date) { if (!is_string($birth_date)) { throw new Exception('Not a string.'); } if (!preg_match('/(\d{4})-([01]\d)-([0-3]\d)/', $birth_date)) { throw new Exception('Not a valid date.'); } $this->birth_date = $birth_date; } public function set_death_date($death_date)
Tags (comma-separated)
Save Edits
Cancel