php - How to best use OOP principles to deal with a case of having 10-15+ matching criteria that all need to be passed? -
i have class takes in lines of text , uses 15 different "criteria" (individual preg_match statements) check if line should qualify saved in array.
how 1 best handle such situation clean, maintainable code?
initially had crazy long if statement had criteria, example:
if ( preg_match($criteria1,$line) && preg_match($criteria2, $line) && ... ... ... preg_match($criterian,$line) ) { //do something, e.g. save line array. }
i've since put each preg_match statement different function within separate class , call each function in row, checking if it's true... have 15 separate functions subtly different each other , still doesn't feel i'm writing code. how best handle situation?
well, if want keep things object oriented, use class this...
class validator{ /* criteria needing met must exist in array */ public static $criterias = array($criteria1, $criteria2, ... , $criterian); public static function validate($line){ /* make sure line meets each criteria */ foreach(validator::$criterias $criteria){ if(!preg_match($criteria, $line)) return false; } return true; }
it makes sense have methods , properties static because unique no instance. can check see if line meets criteria calling
validator::validate($line)
Comments
Post a Comment