I have just refactored a php page to make it slightly easier to extend and maintain in the future and gotten stuck on quite a simple problem.
I have broken one method up into 3.
largemethod() has become something like this:
nowsmallmethod(){
doSomeChecks();
assignProduct();
giveFeedbacktoUser();
}
This is all good and well, the problem I am having is with doSomeChecks();
doSomeChecks(){
if(something that shouldnt be true is true){
return Controller->redirectBk();
}
}
The crux of the problem is that Controller-redirectBk first redirects when nowsmallmethod() has been completed. This means that the user is assigned a product even if a test fails. I am using a php framework called Silverstripe so I cant really change the behavior of Controller->redirectBk(). If I didnt have the checks in their own method then everything would work fine because the "return Controller->redirectBk();" would stop execution and redirect back. Whats the best way to stop execution in nowsmallmethod() when a test fails? I realise i could return a status code for an error and then stop execution but it seems an ugly way. Is there not a more elegant way? Another option would be if i could return something like this in doSomeChecks(), "return (return $controller->redirectBk())" but this is not valid php syntax and not particularly easy to read. Any help would be hugely appreciated.
Enjoy your weekend! Cheers Nick
nowsmallmethod() {
if (doSomeChecks()) {
assignProduct();
giveFeedbacktoUser();
}
}
And doSomeChecks
either returns true or false, based on whether the redirect will happen or not.
Alternatively, you could die
or throw
, but I assume a normal condition is more suitable in your case.
Use exceptions to handle situations like that:
<?php
try {
// some code
if (!$check) {
throw new Exception('Check has failed!');
}
// code after 'throw' will not be executed
}
catch(Exception $e) {
//this is executed when exception is caught
}
?>
If the exception is thrown in child method, the stack will roll back to the very first try/catch block. read more about the exceptions: http://php.net/manual/en/language.exceptions.php
Also, you can combine exceptions with transaction mechanism to handle database integrity.