35、Hyperf 3 快速使用 - Hyperf 3 使用枚举类

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 318

时间: 2023-04-25 16:15:13

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握枚举类的使用

本篇文章将结合异常演示通过不同的状态码输出不同的数据。

第一步:安装组件

composer require hyperf/constants

第二步:生成枚举类

php bin/hyperf.php gen:constant PostStatusCode

该命令会在 app/Constants 目录下生成 PostStatusCode.php 文件。

第三步:编写生成的枚举类

<?php

declare(strict_types=1);

namespace App\Constants;

use Hyperf\Constants\AbstractConstants;
use Hyperf\Constants\Annotation\Constants;

#[Constants]
class PostStatusCode extends AbstractConstants
{
    /**
     * @Message("草稿")
     */
    const DRAFT = 1;

    /**
     * @Message("发布")
     */
    const PUBLISHED = 2;
}

第四步:定义 API 异常类

1、定义异常 Handler

<?php

namespace App\Exception\Handler;


use App\Constants\ErrorCode;
use App\Constants\PostStatusCode;
use App\Exception\ApiException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class ApiExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof ApiException) {
            $data = json_encode([
                'code'    => $throwable->getCode(),
                // 通过状态码获取枚举信息
                'message' => PostStatusCode::getMessage($throwable->getCode()),
            ], JSON_UNESCAPED_UNICODE);


            $this->stopPropagation();

            return $response->withStatus(500)->withBody(new SwooleStream($data));
        }

        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}

2、定义异常

<?php

namespace App\Exception;

use Hyperf\Server\Exception\ServerException;
class ApiException extends ServerException
{
}

3、注册异常

<?php
// config/autoload/exceptions.php
    
declare(strict_types=1);

return [
    'handler' => [
        'http' => [
            Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,
            // 添加 API 异常
            \App\Exception\Handler\ApiExceptionHandler::class,
        ],
    ],
];

第五步:控制器使用枚举类

<?php
// App\Controller\demo\TestController.php 

use App\Constants\PostStatusCode;
    
#[GetMapping('/test/error')]
public function error(RequestInterface $request)
{
    $status = (int) $request->input('status', 1);

    $code = match ($status) {
        1 => PostStatusCode::DRAFT,
        2 => PostStatusCode::PUBLISHED,
        default => PostStatusCode::DRAFT,
    };
	
    throw new ApiException(PostStatusCode::getMessage($code), $code);
}

第六步:测试

$ curl http://192.168.31.90:9501/test/error?status=1
{"code":1,"message":"草稿"}
$ curl http://192.168.31.90:9501/test/error?status=2
{"code":2,"message":"发布"}

本篇文章到此结束,我是温新。

请登录后再评论