dousha7645 2011-01-22 23:11
浏览 26
已采纳

在重构的PHP代码中停止执行?

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

  • 写回答

2条回答 默认 最新

  • dongxing1412 2011-01-22 23:19
    关注
    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?