1. 在common/library 中定义Response.php响应文件
<?php
namespace app\common\library;
class Response
{
const JSON = "json";
/**
* 按综合方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* @param string $type 数据类型
* return string
*/
public function show(int $code, string $message = '', array $data=[], string $type = self::JSON)
{
if(!is_numeric($code)) {
return '';
}
if($type == 'json') {
self::json($code, $message, $data);
exit;
} elseif($type == 'array') {
return $type;
} elseif($type == 'xml') {
self::xmlEncode($code, $message, $data);
exit;
} else {
return "";
}
}
/**
* 按json方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* return string
*/
public static function json(int $code, string $message = '', array $data = array()) {
if(!is_numeric($code)) {
return '';
}
$result = array(
'code' => $code,
'message' => urlencode($message),
'data' => $data
);
echo urldecode(json_encode($result,JSON_UNESCAPED_UNICODE));
exit;
}
/**
* 按xml方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* return string
*/
public static function xmlEncode(int $code, string $message, array $data = array()): string
{
if(!is_numeric($code)) {
return '';
}
$result = array(
'code' => $code,
'message' => $message,
'data' => $data,
);
header("Content-Type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xmlToEncode($result);
$xml .= "</root>";
return $xml;
}
public static function xmlToEncode($data): string
{
$xml = $attr = "";
foreach($data as $key => $value) {
if(is_numeric($key)) {
$attr = " id='{$key}'";
$key = "item";
}
$xml .= "<{$key}{$attr}>";
$xml .= is_array($value) ? self::xmlToEncode($value) : $value;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
2. 在common/facade中在定义一个?Response.php代理文件
<?php
namespace app\common\facade;
use think\Facade;
class Response extends Facade
{
protected static function getFacadeClass(): string
{
return 'app\common\library\Response';
}
}
3.控制器中调用
?
use app\common\facade\Response;
use think\facade\Request;
use app\land\model\LandContractor as modelLandContractor;
use think\response\Json;
class LandContractor
{
/**
* @purpose 获取某个人的所有地块信息
* @return Json
* @author 墨竹 <1030200727@qq.com>
* @date 2022/4/11
* @time 19:13
*/
public function getAllTraceLand() :Json
{
$params=Request::param('user_id');
$modelLandContractor=new modelLandContractor();
$data=$modelLandContractor->getLand($params);
if ($data){
return Response::show(200,'请求成功',$data);
}else{
return Response::show(201,'请求失败',[]);
}
}
}
?
|