ResultCode和HTTP定义的status_code (状态码)不同,ResultCode表示的是后端控制器处理后返回给前端结果码
Exception.php
<?php
namespace app\exception;
class Exception extends \Exception
{
public function __construct($message, $code = -1, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
Enum.php
<?php
namespace app\enums;
use app\exception\Exception;
class Enum
{
private static function getConstants()
{
$class = new \ReflectionClass(get_called_class());
return $class->getConstants();
}
public static function isValidKey($key)
{
$constants = self::getConstants();
return array_key_exists($key, $constants);
}
public static function isValidValue($value)
{
$constants = array_values(self::getConstants());
return in_array($value, $constants);
}
public static function getValue($key)
{
$class = get_called_class();
if(self::isValidKey($key)){
$value = @eval('return $class::' . $key . ';');
return $value;
}else{
$message = "Undefined constant `{$key}` in class " . $class;
throw new Exception($message);
}
}
public static function getKey($value)
{
$class = get_called_class();
$constants = self::getConstants();
$key = array_search($value,$constants);
if($key){
return $key;
}else{
$message = "Undefined value `{$value}` in class " . $class;
throw new Exception($message);
}
}
}
ResultCode.php
//结果码
class ResultCode extends Enum
{
const SUCCESS = 1;
//参数错误
const PARAMS_ERROR = 10000;//参数错误(大类)
const PARAMS_IS_INVALID = 10001;//参数无效
const PARAMS_NOT_COMPLETE = 10002;//参数不全
//数据错误
const DATA_ERROR = 20000;//数据错误(大类)
const DATA_NOT_FOUND = 20001;//数据没找到
const DATA_ALREADY_EXISTED = 20002;//数据已存在
const DATA_IS_WRONG = 20003;//数据有错误
//业务错误
const BUSINESS_ERROR = 30000;//业务错误(大类)
//更多......
}
尽可能使用5位以上数字方便后面扩展
如果不想分得太细,直接使用大类的结果码亦可
Result.php
<?php
namespace app\web;
use Yii;
use app\enums\ResultCode;
class Result
{
public $code;
public $message;
public $data;
public function __construct($code = '', $message = '', $data = null)
{
$this->code = $code;
$this->message = $message;
$this->data = $data;
}
}
SuccessResult.php
<?php
namespace app\web;
use Yii;
use app\enums\ResultCode;
class SuccessResult extends Result
{
public function __construct($data = null)
{
parent::__construct(ResultCode::SUCCESS,'',$data);
}
}
FailResult.php
<?php
namespace app\web;
use Yii;
use app\enums\ResultCode;
class FailResult extends Result
{
public function __construct($code,$data = null)
{
$message = ResultCode::getKey($code);
parent::__construct($code,$message,$data);
}
}
ResponseResult.php
<?php
namespace app\web;
use Yii;
//响应结果
class ResponseResult
{
public static function send($result)
{
$response = Yii::$app->response;
$response->data = $result;
$response->send();
}
public static function success($data = null)
{
$result = new SuccessResult($data);
self::send($result);
}
public static function fail($code,$data = null)
{
$result = new FailResult($code,$data);
self::send($result);
}
}
用法
ResponseResult::success();
ResponseResult::fail(ResultCode::PARAMS_ERROR);
|