自定义rest api的基本思想过程--总结
技术栈:tp51. ,mysql
写一个接口最基本的过程
自定义路由->验证参数->异常抛出->写入日志
tp5.1手册https://www.kancloud.cn/manual/thinkphp5_1/354102
下面只是就基本的应用,其实路由,验证器,异常都能单独一篇
自定义路由

自定义验证器
个人习惯吧,看别人都是把一个验证器成一个文件,但是我不喜欢,相比之下,我更喜欢文件越少越好,但是

<?php
namespace app\api\controller\validate;
use think\Validate;
class ValidateHandler extends Validate
{
protected $rule = [
"id" => "require|isPositiveInteger",
]; // 默认验证规则
// 自定义验证规则
private $allRule = [
// id必须是正整数
'isPositiveInteger' => [
"id" => "require|isPositiveInteger",
],
'demo' => [
"id2" => "require",
]
];
//验证参数的函数
public function goCheck()
{
// 1,获取所有传递过来的参数
$request = input("param.");
// 2,筛选所有数据
$result = $this->batch()->check($request);
dump($this->error);
// if ($result) {
// return true;
// } else {
// // 抛出自定义异常
// }
}
/**
* 修改验证器规则
* @param string $rulename 自定义验证规则的键
*/
public function __construct($rulename='')
{
// 判断所有验证器中是否有需要的值
if(array_key_exists($rulename,$this->allRule)){
$this->rule = $this->allRule[$rulename];
}
}
/********************************************* 自定义验证函数 ****************************************************************/
// 必须是正整数
protected function isPositiveInteger($value, $rule = '', $data = '', $field = '')
{
// 匹配一个开头为1-9,且开头之后到结尾0或多个0-9 -》正整数
// 现在在5.1版本中 路由直接定义规则 也就是说这个判断可以不需要
if (preg_match("/^[1-9][0-9]*$/", $value)) {
// die('是正整数');
return true;
} else {
return $field . '必须是正整数';
}
}
}
调用
<?php
namespace app\api\controller\v1;
use app\api\controller\validate\ValidateHandler;
class Banner
{
/**
* 获取指定的banner
* @url /banner/:id
* @http EGT
* @param $id
*/
public function getBanner($id)
{
// 验证参数
(new ValidateHandler())->goCheck();
(new ValidateHandler("demo"))->goCheck();
}
}
返回

自定义异常抛出

<?php
namespace app\lib\exception;
use Exception;
use think\exception\Handle;
use think\facade\Request;
class ExceptionHandler extends Handle
{
private $code; //http状态码200,404
private $msg; // 返回的信息
private $errorCode; // 自定义状态码
// 1, 改写render方法,所有异常处理都会经过这个函数
public function render(Exception $e)
{
// 2, 判断是否是代码错误还是说服务器错误,如果 调用的BaseException说明这是自己抛出的异常,否则则是其他方式 出现的错误
if ($e instanceof BaseException) {
// 3.1 自定义的异常
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
} else {
// return parent::render($e); // TODO: Change the autogenerated stub
// 3.2 不是自己主动抛出的异常
$this->code = 500;
$this->msg = '服务器内部错误,不想告诉你 (^o^)Y';
$this->errorCode = 999;
}
// 4,获取需要返回的错误信息
$url = Request::url();
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request_url' => $url
];
return json($result, $this->code);
}
}
<?php
namespace app\lib\exception;
use think\Exception;
class BaseException extends Exception
{
// 定义的所有异常,每个都可以修改
public $allException = [
"paramsErr" => [
"code" => 400,
'msg' => '参数错误',
'errorCode' => 10000
],
"BannerMiss" => [
"code" => 404, // http状态码
'msg' => '请求的banner不存在', // 错误描述
'errorCode' => 40000
]
];
// 默认异常
public $code = 400; //http状态码
public $msg = '参数错误'; // 错误描述
public $errorCode = 10000; //自定义错误吗
/**
* 修改验证器规则
* @param string $rulename 自定义验证规则的键
* @param string $params 关联数组只应包含code、msg和errorCode,且不应该是空值
*/
public function __construct($rulename = '', $params = [])
{
// 判断所有验证器中是否有需要的值
if ($rulename && array_key_exists($rulename, $this->allException)) {
$info = $this->allException[$rulename];
$this->code = $info["code"];
$this->msg = $info['msg'];
$this->errorCode = $info['errorCode'];
}
if (!is_array($params)) {
return;
}
if (array_key_exists('code', $params)) {
$this->code = $params['code'];
}
if (array_key_exists('msg', $params)) {
$this->msg = $params['msg'];
}
if (array_key_exists('errorCode', $params)) {
$this->errorCode = $params['errorCode'];
}
}
}
使用

写入日志

浙公网安备 33010602011771号