关于hyperf:hyperf-框架完善之枚举类和公共函数库连载中
转发自白狼栈:查看原文 明天咱们来看两个问题,枚举类和公众函数库的引入。 枚举类上节课最初咱们抛出的问题其实就是如何自定义 code 的问题。 为了方便管理错误码,咱们利用 hyperf 的枚举类进行治理。 枚举类参考 https://hyperf.wiki/3.0/#/zh-...枚举类依赖 hyperf/constants 组件,composer require 进行装置。 composer require hyperf/constants:3.0.*生成枚举类 php bin/hyperf.php gen:constant ErrorCode生成好的 ErrorCode 类批改如下: <?phpdeclare(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 后果如下: ...