Problem
I would like to make a function that checks if something is valid, but if it can’t then I want to return an error message that will probably be used to to throw an exception.
public function isTodayWithinDateRange(DateTime $start, DateTime $end) {
$now = new DateTime();
if($now >= $start && $now <= $end) return true;
if($now < $start) return 'Today is before the start date';
if($now > $end) return 'Today is later than the end date';
}
And would probably use within a foreach as a validation check such as…
if(isTodayWithinDateRange($myStart, $myEnd) !== true) {
throw new Exception(isTodayWithinDateRange($myStart, $myEnd));
}
Is this a good way to go about it? I thought about putting the exception within the function, but this doesn’t seem right as all that function should be doing is doing a check and the thing calling it should decide if an error is exceptional or not.
I also thought about returning an array such as…
return array(
'success' => false,
'error' => 'Today is later than the end date'
);
But I would expect isTodayWithinDateRange to return true
if the answer is ‘yes’.
Solution
Simply , the method isTodayWithinDateRange can throw the exception in this case since the responsability of the method is to check the constraint .
So , i think that you can try it as :
function isTodayWithinDateRange(DateTime $start, DateTime $end) {
$now = new DateTime();
if($now < $start) throw new Excception('Today is before the start date') ;
if($now > $end) throw new Exception('Today is later than the end date');
return true;
}
First , start with case where you are looking to throw exception , in this case , it’s not clearly , but think about a case where you have a lot of logic , here you should start with cases where you don’t need to manipulate your logic (like if the argument is null , or missing …) .
Call you method as :
$myStart = new Datetime('01-06-2012');
$myEnd = new Datetime('01-06-2020');
// loop
try{
if(isTodayWithinDateRange($myStart, $myEnd)) {
echo 'contraint validated';
}
}catch(Exception $e){
echo $e->getMessage();
}
//end loop
I hope this help you .