限时 5折! 详情

hyperf 框架完善之枚举类和公共函数库

1389 0 0

今天我们来看两个问题,枚举类和公众函数库的引入。

枚举类

上节课最后我们抛出的问题其实就是如何自定义 code 的问题。

为了方便管理错误码,我们利用 hyperf 的枚举类进行管理。

枚举类参考 https://hyperf.wiki/3.0/#/zh-cn/constants

枚举类依赖 hyperf/constants 组件,composer require 进行安装。

composer require hyperf/constants:3.0.*

生成枚举类

php bin/hyperf.php gen:constant ErrorCode

生成好的 ErrorCode 类修改如下:

<?php
declare(strict_types=1);

namespace App\Constants;

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

#[Constants]
class ErrorCode extends AbstractConstants
{
    /**
     * @Message("Server Error!")
     */
    const SERVER_ERROR = 500;

    /**
     * @Message("params.id_invalid")
     */
    const PARAMS_ID_INVALID = 100001;
}

如上,我们增加了 PARAMS_ID_INVALID=100001 用来定义“id无效”,可以使用 ErrorCode::getMessage(ErrorCode::PARAMS_ID_INVALID) 来获取对应错误信息。

IndexService::info 修改如下:

use App\Constants\ErrorCode;

public function info(int $id)
{
    if ($id <= 0) {
        // throw new BusinessException(trans('params.id_invalid'));
        throw new BusinessException(ErrorCode::getMessage(ErrorCode::PARAMS_ID_INVALID));
    }

    return ['info' => 'data info'];
}

curl 结果如下:

✗ curl http://127.0.0.1:9501/index/info\?id\=0 --header "lang:ja"
{"code":0,"message":"ID が無効です"}%

ErrorCode::PARAMS_ID_INVALID 的定义直接就支持了国际化,这一点非常友好。但是并没有改变 code=0 的现状。

稍微优化下 BusinessException 如下:

class BusinessException extends ServerException
{
    public function __construct(int $code = 0, string $message = null, \Throwable $previous = null)
    {
        if (is_null($message)) {
            $message = ErrorCode::getMessage($code);
        }

        parent::__construct($message, $code, $previous);
    }
}

IndexService::info 改写如下:

public function info(int $id)
{
    if ($id <= 0) {
        // throw new BusinessException(trans('params.id_invalid'));
        // throw new BusinessException(ErrorCode::getMessage(ErrorCode::PARAMS_ID_INVALID));
        throw new BusinessException(ErrorCode::PARAMS_ID_INVALID);
    }

    return ['info' => 'data info'];
}

curl 测试结果如下:

✗ curl http://127.0.0.1:9501/index/info\?id\=0 --header "lang:ja"
{"code":100001,"message":"ID が無効です"}%

公共函数库的引入

我们在 AppExceptionHandler::handle 方法中使用过一个函数, 最后一行代码 env('APP_ENV') == 'dev' 。

这里的 env 函数是在 vendor/hyperf/utils/src/Functions.php 文件内定义的。

在这个文件中,hyperf 官方定义了很多函数,在我们的项目中,同样也需要定义一些函数。比如我们封装一个将字节转化成 KB 或者 MB 的函数 convert_size,总不能去改 hyperf 官方的源码包,在 vendor/hyperf/utils/src/Functions.php 文件内添加吧。

这个很简单,利用 composer 的自动加载机制即可。

app 下创建新的目录文件 app/Utils/Functions.php,内容如下:

<?php

if (! function_exists('convert_size')) {
    /**
     * 将字节转化为 kb mb 等单位
     * @param $size
     * @return string
     */
    function convert_size($size)
    {
        $unit = ['b', 'kb', 'mb', 'gb', 'tb', 'pb'];
        return @round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[$i];
    }
}

修改根目录下的 composer.json 文件中的 autoload 项如下:

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Utils/Functions.php"
    ]
},

修改 composer.json 后还需要执行 composer dump-autoload -o 命令。

/data/project/questions # composer dump-autoload -o
Generating optimized autoload files
> rm -rf runtime/container
Generated optimized autoload files containing 3132 classes

改写 IndexController::info 方法:

#[AutoController]
class IndexController extends AbstractController
{
    public function info()
    {
        return convert_size(memory_get_usage(true));
    }
}

curl 结果:

✗ curl 127.0.0.1:9501/index/info
8 mb%

至此,框架的基本结构我们就完善的差不多了,下节课我们补充一些 swoole 协程方面的知识。

立即购买