Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
停止重构php代码中的执行?_Php_Oop_Testing_Refactoring - Fatal编程技术网

停止重构php代码中的执行?

停止重构php代码中的执行?,php,oop,testing,refactoring,Php,Oop,Testing,Refactoring,我刚刚对一个php页面进行了重构,使其在将来的扩展和维护变得稍微容易一些,但遇到了一个相当简单的问题 我把一种方法分成了三种 largemethod()变成了这样: nowsmallmethod(){ doSomeChecks(); assignProduct(); giveFeedbacktoUser(); } 这一切都很好,我遇到的问题是doSomeChecks() 问题的关键是控制器redirectBk在nowsmalMethod()完成时首先重定向。这意味着即使测试失败,用

我刚刚对一个php页面进行了重构,使其在将来的扩展和维护变得稍微容易一些,但遇到了一个相当简单的问题

我把一种方法分成了三种

largemethod()变成了这样:

nowsmallmethod(){
  doSomeChecks();
  assignProduct();
  giveFeedbacktoUser();
}
这一切都很好,我遇到的问题是doSomeChecks()

问题的关键是控制器redirectBk在nowsmalMethod()完成时首先重定向。这意味着即使测试失败,用户也会被分配产品。我使用的是一个名为Silverstripe的php框架,因此我无法真正更改Controller->redirectBk()的行为。如果我没有在自己的方法中进行检查,那么一切都会正常工作,因为“returncontroller->redirectBk();”将停止执行并重定向回当测试失败时,在nowsallmethod()中停止执行的最佳方法是什么?我意识到我可以返回错误的状态码,然后停止执行,但这似乎是一种丑陋的方法。难道没有更优雅的方式吗?另一个选项是,如果我可以在doSomeChecks()中返回类似的内容,“return(return($controller->redirectBk()”),但这不是有效的php语法,也不太容易阅读。任何帮助都将不胜感激

祝你周末愉快! 干杯 尼克

doSomeChecks
根据重定向是否发生,返回true或false


或者,您可以
死亡
抛出
,但我认为正常情况更适合您的情况。

使用异常处理类似情况:

<?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
}
?>

如果在子方法中抛出异常,堆栈将回滚到第一个try/catch块。了解有关例外情况的更多信息:


此外,您还可以将异常与事务机制结合起来处理数据库完整性。

异常适用于异常情况,例如您试图获取某些资源但失败的情况。我不认为是这样。嘿,谢谢你的建议。其中有一些检查抛出异常、安全测试等,但大多数设置了一条userfeedback会话消息,然后简单地将该消息返回给用户。它们并不真正适合于异常。这在功能上相当于返回错误代码。我只是想也许有更好的方法,但也许没有。在这种情况下,任何失败的测试都必须设置$controller->redirectBk(),然后返回false。为你的建议干杯
nowsmallmethod() {
  if (doSomeChecks()) {
    assignProduct();
    giveFeedbacktoUser();
  }
}
<?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
}
?>