0

给定一个循环,向数组中的所有订阅发送电子邮件

foreach($subscriptions as $s){
    if(!$s->send_email()){

    }
}

如果所有模型都已成功邮寄或如果其中一个模型未能邮寄则显示错误,那么触发回调的最干净的方法是什么。将所有错误消息保存到循环结束并将它们作为一个整体打印,或者以错误中断循环是常见的吗?

我将它与保存项目 (/projects/1) 的 JSON REST API 结合使用,该项目又向所有用户发送电子邮件。

我现在使用的方法感觉很脏,有很多嵌套的 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
}

我想知道关于这个的约定是什么

4

2 回答 2

1

它有点混乱——它在“保存”功能中结合了多个关注点——任何阅读代码的人都需要了解“保存”的含义,我们如何遍历联系人等。

我将它重构如下:

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
    }

}
于 2012-08-09T10:43:37.913 回答
0

您可以使用 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;
}
于 2012-08-09T08:58:33.483 回答