PHP code example of felo-z / hyperf-api-response

1. Go to this page and download the library: Download felo-z/hyperf-api-response library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

felo-z / hyperf-api-response example snippets


use FeloZ\HyperfApiResponse\Support\ApiCode;

api_response()->ok(['id' => 1], 'ok');
api_response()->success(['id' => 1], 'success');
api_response()->message('创建成功', ['id' => 1], 201);
api_response()->failed('参数错误', ApiCode::BIZ_FAILED, 400, ['field' => 'name']);
api_response()->exception($throwable);

public function show(int $id)
{
    return api_response()->ok(['id' => $id]);
}

// app/Support/ApiCodes/UserCode.php
final class UserCode
{
    public const NOT_FOUND = 200404;
}

// 使用
return api_response()->failed('用户不存在', UserCode::NOT_FOUND, 400);

// config/autoload/exceptions.php
return [
    'handler' => [
        'http' => [
            // 可选:项目自定义业务异常(只处理特定异常类)
            // App\Exception\Handler\BizExceptionHandler::class,

            // 本包:API 统一 JSON(应在 HttpExceptionHandler 之前)
            \FeloZ\HyperfApiResponse\Exception\Handler\ApiExceptionHandler::class,

            // 框架默认
            Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,

            // 项目兜底
            App\Exception\Handler\AppExceptionHandler::class,
        ],
    ],
];

var_dump(config('exceptions.handler.http'));

[
    0 => 'FeloZ\HyperfApiResponse\Exception\Handler\ApiExceptionHandler',
    1 => 'Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler',
    2 => 'App\Exception\Handler\AppExceptionHandler',
]

return [
    'enable_exception_handler' => env('API_RESPONSE_ENABLE_EXCEPTION_HANDLER', true),
    'render_api_paths' => ['/api/*'],
    'hide_error_when_not_debug' => env('API_RESPONSE_HIDE_ERROR', true),
    'pipes' => [...],
    'exception_pipes' => [...],
];
bash
php bin/hyperf.php vendor:publish felo-z/hyperf-api-response