Php 使用条件重构循环
给定一个向数组中的所有订阅发送电子邮件的循环Php 使用条件重构循环,php,Php,给定一个向数组中的所有订阅发送电子邮件的循环 foreach($subscriptions as $s){ if(!$s->send_email()){ } } 如果所有模型都已成功发送邮件,那么触发回调的最干净方法是什么?如果其中一个模型未能发送邮件,那么触发回调的最干净方法是什么。将所有错误消息保存到循环结束并将其作为一个整体打印,或者使用错误中断循环,这是常见的做法 我将它与一个JSON REST API结合使用,保存一个项目(/projects/1),然后通过电
foreach($subscriptions as $s){
if(!$s->send_email()){
}
}
如果所有模型都已成功发送邮件,那么触发回调的最干净方法是什么?如果其中一个模型未能发送邮件,那么触发回调的最干净方法是什么。将所有错误消息保存到循环结束并将其作为一个整体打印,或者使用错误中断循环,这是常见的做法
我将它与一个JSON REST API结合使用,保存一个项目(/projects/1),然后通过电子邮件发送给所有用户
我现在使用的方法感觉脏兮兮的,有很多嵌套的if-else,在不同的地方发送3个不同的响应
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
if(count($errors) > 0){
//send json api response with error response
} else {
//send json api success response
}
} else {
//send json api response with project error response
}
我想知道关于这一点,您可以使用while逻辑的约定是什么,这样故障就会一直持续到块的末尾
while(1) {
if ($project->save()) {
foreach($subscripts as $s)
if (!$s->send_email())
$errors[] = "failed to send email. Subscription ". $s->id;
} else
$errors[] = 'failed to save the project';
if (empty($errors)) {
//send success here
break;
}
//send your errors here
break;
}
它有点混乱——它在“save”函数中结合了多个关注点——任何阅读代码的人都需要理解“save”是什么意思,我们如何循环浏览联系人等等 我将按如下方式重构它:
if($project->save()){
$subscriptions = Subscription::model()->findAllByAttributes(array('planning_id' => $planning->id));
$errors = sendMailToSubscribers($subscriptions);
$response = determineResponse($errors);
// send JSON API response
} else {
//send json api response with project error response
}
function sendMailToSubscribers($subscriptions){
foreach($subscriptions as $s){
if(!$s->send_email()){
$errors[] = "failed to send email. Subscription ". $s->id;
}
}
return $errors;
}
function determineResponse($errors){
if(count($errors) > 0){
//return json api response with error response
} else {
//return json api success response
}
}
我认为这取决于错误的严重程度。。。你想在一个错误后停止还是继续并在结束时报告错误?IMO这不是一个编程决策,而是一个商业决策……这不是“惯例”,而是行为。您希望这里有什么样的行为-如果邮件无法发送,您希望中断并停止尝试发送更多邮件,还是希望尝试发送所有邮件并稍后处理错误?一般来说,我倾向于后一种选择,但这完全取决于你想如何处理它。我认为你是对的。这感觉很难看,所以我认为应该有一个更干净的方法,两种解决方案都有其优点和缺点。也许除了我提到的两个,还有另一个解决方案。我喜欢你创建一个独立的响应函数。我想如果你再重构一点,你就会在那里$response=sendMailToSubscribers($subscriptions)//$响应为{“error”:“error message”}或数据本身API::sendResponse($response);并且让api检测对象中是否有“错误”或只是普通数据。基于此,可以将标题设置为200或404/401/500