2016-04-18 4 views
1

Я делал рефакторинг кода в проекте в структуре Yii2.рефакторинг простого кода в Yii2 (if-else)

Я просто спрашиваю, может ли это быть написано лучше, с меньшим количеством повторений (я стараюсь следовать DRY всякий раз, когда могу). Любая рекомендация по литературе по этой теме более чем приветствуется, извините за плохой английский.

$exception = Yii::$app->errorHandler->exception; 

    if ($exception !== null) { 
     if (isset($exception->statusCode)) { 
      if ($exception->statusCode == 500) { 
       return $this->render('error-500', ['exception' => $exception]); 
      } elseif ($exception->statusCode == 404) { 
       return $this->render('error-404', ['exception' => $exception]); 
      } else { 
       return $this->render('error', ['exception' => $exception]); 
      } 
     } elseif (isset($exception->code)) { 
      if ($exception->code == 500) { 
       return $this->render('error-500', ['exception' => $exception]); 
      } elseif ($exception->code == 404) { 
       return $this->render('error-404', ['exception' => $exception]); 
      } else { 
       return $this->render('error', ['exception' => $exception]); 
      } 
     } 
    } else { 
     $exception = new \yii\web\HttpException(500); 
     return $this->render('error-500', ['exception' => $exception]); 
    } 

ответ

2

Вы можете сделать это, если вам нравится

$exception = Yii::$app->errorHandler->exception; 

    if ($exception !== null) { 
     if (isset($exception->statusCode){ 
      return $this-render('error-' . $exception->statusCode , ['exception' => $exception]); 
     } else if (isset($exception->code)) { 
      return $this-render('error-' . $exception->code , ['exception' => $exception]) 
     } else { 
     $exception = new \yii\web\HttpException(500); 
     return $this->render('error-500', ['exception' => $exception]); 
     } 
    } 

или так, если, как более компактный

if ($exception !== null) { 
     if (isset($exception->statusCode, $exception->code){ 
      return $this-render('error-' . ($exception->statusCode) ? $exception->statusCode : $exception->code , ['exception' => $exception]); 
     } else { 
     $exception = new \yii\web\HttpException(500); 
     return $this->render('error-500', ['exception' => $exception]); 
     } 
    } 
+0

Спасибо и Vm человек. Мой ум прекратился после 10 часов работы. –

+0

Мне повезло, что мой ум остановился после 8 часов работы – scaisEdge

1

Другой возможный путь

 if ($exception !== null) { 

     $exceptionCode = isset($exception->statusCode)?$exception->statusCode: 
       (isset($exception->code)?$exception->code:null); 

     if($exceptionCode){ 
      $viewFile = ($exceptionCode == 500)?'error-500': 
        (($exceptionCode == 404)?'error-404':'error'); 

      return $this->render($viewFile, ['exception' => $exception]); 

     } else { 
      // you need to something here 
     } 

    } 
Смежные вопросы