重构Yii2中的简单代码(if-else)

时间:2016-04-18 14:48:58

标签: yii2 refactoring

我正在对Yii2框架中的项目进行一些代码重构。

我只是问这是否可以写得更好,重复次数更少(我尽量跟随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 个答案:

答案 0 :(得分: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]);
        }
    }

答案 1 :(得分: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
        }

    }