hyperf框架基础建设:返回统一json对象

<?php

namespace App\common\response;


use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;

/**
 * 统一返回类
 */
class RespResult
{

    /**
     * 成功
     * @return Psr7ResponseInterface
     */
    public static function success(){
        $data = json_encode(["code"=>SystemCode::SYSTEM_SUCCESS,"message"=>SystemMessage::SYSTEM_SUCCESS,"data"=>[]],JSON_UNESCAPED_UNICODE);
        return self::response($data);
    }


    /**
     * 失败
     * @return Psr7ResponseInterface
     */
    public static function error(){
        $data = json_encode(["code"=>SystemCode::SYSTEM_ERROR,"message"=>SystemMessage::SYSTEM_ERROR,"data"=>[]],JSON_UNESCAPED_UNICODE);
        return self::response($data);
    }


    /**
     * 自定义返回
     * @param string $code
     * @param string $message
     * @param array $data
     * @return Psr7ResponseInterface
     */
    public static function result(string $code,string $message,array $data = []){
        $data = json_encode(["code"=>$code,"message"=>$message,"data"=>$data],JSON_UNESCAPED_UNICODE);
        return self::response($data);
    }


    /**
     * 统一响应数据
     * @param $data
     * @return Psr7ResponseInterface
     */
    private static function response($data){
        $response = self::container()->get(ResponseInterface::class);
        return $response->withAddedHeader('content-type', 'application/json; charset=utf-8')->withBody(new SwooleStream($data));
    }

    /**
     * 容器实例
     * @return \Psr\Container\ContainerInterface
     */
    private static function container()
    {
        return ApplicationContext::getContainer();
    }



}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值