I would suggest using the Factory template and storing the json object in the database containing instructions for creating the filter. The json object will be retrieved from the database and passed to Factory, which will create the correct type of Filter object.
Suppose you have two filters that use a regular expression and the other for a range of values. Then you can create each filter as follows:
class Filter{ public function filter($results){ $filteredResults = array(); foreach($results as $item){ if($this->isMatch($item)){ $filteredResults[]=$item; } } return $filteredResults } public function isMatch($row){ return true; } } class RegexFilter extends Filter{ public function __construct($regexString){ $this->regex = $regexString; } public function isMatch($item){ return preg_match($this->regex,$item) ==1; } } class RangeFilter extends Filter{ public function __construct($min,$max){ $this->max = $max; $this->min = $min; } public function isMatch($item){ return $this->min < $item && $item <$this->max; } } class FilterFactory{ public function createFilter($json){ $filterData = json_decode($json); if($filterData->filterType == 'regex'){ return new RegexFilter($filterData->regexStr); } elseif($filterData->filterType == 'range'){ return new RangeFilter($filterData->min,$filterData->max); } } }
This approach allows you to use best practices to support your code base while storing filtering instructions in your database.
The child classes use the Filter filter method, but their own isMatch method, which makes it easy to add new filters. You simply A) inherit from the Filter class and implement the new isMatch method; B) add a new sentence to FilterFactory->createFilter to create the filter correctly, and C) add Json describing the filter to the database.
Everywhere you can use the same logic to filter results:
$filter=FilterFactory::createFilter($jsonFromDatabase); $filteredResults = $filter->filter($resultsFromApi);
rulio
source share