一、统一响应接口
- 新增 App\Components\Response
预设一个成功返回接口,一个失败接口。
namespace App\Components;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
class Response
{
/**
* @Inject()
* @var ResponseInterface
*/
protected $response;
public function success($data = [])
{
return $this->response->json([
'code' => 0 ,
'data' => $data ,
]);
}
public function error($code , $msg = 'error')
{
return $this->response->json([
'code' => $code ,
'msg' => $msg ,
]);
}
}
- 将 App\Controller\AbstractController 的 注入的RequestInterface 改为上一步新增的 Response 类
namespace App\Controller;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use App\Components\Response;
use Psr\Container\ContainerInterface;
abstract class AbstractController
{
/**
* @Inject
* @var ContainerInterface
*/
protected $container;
/**
* @Inject
* @var RequestInterface
*/
protected $request;
/**
* @Inject
* @var Response
*/
protected $response;
}
- 任意接口进行测试
public function songs()
{
return $this->response->success(1);
}
二、自定义异常处理
- 屏蔽源码异常处理
找到异常处理配置文件,conf/autoload/exception,注释掉 HttpExceptionHandler
return [
'handler' => [
'http' => [
// Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
],
],
];
- 创建自定义业务异常处理类
namespace App\Exception;
use Hyperf\Server\Exception\ServerException;
class BusinessException extends ServerException
{
}
- 修改App\Exception\Handler\AppExceptionHandler
<?php
declare(strict_types=1);
namespace App\Exception\Handler;
use App\Components\Response;
use App\Exception\BusinessException;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Throwable;
use Hyperf\ExceptionHandler\Formatter\FormatterInterface;
class AppExceptionHandler extends ExceptionHandler
{
protected $logger;
protected $response;
public function __construct(StdoutLoggerInterface $logger,Response $response)
{
$this->logger = $logger;
$this->response = $response;
}
public function handle(Throwable $throwable, ResponseInterface $response)
{
$formatter = ApplicationContext::getContainer()->get(FormatterInterface::class);
$errMsg = sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile())
if($throwable instanceof BusinessException){
return $this->response->fail($throwable->getCode(),$errMsg);
}
if($throwable instanceof HttpException){
return $this->response->fail($throwable->getStatusCode(),$errMsg);
}
$this->logger->error($formatter->format($throwable));
return $this->response->fail(500,'Server Error');
}
public function isValid(Throwable $throwable): bool
{
return true;
}
}
可根据环境判断输出错误信息的详细程度。
- 枚举类
composer require hyperf/constants
php bin/hyperf.php gen:constant ErrorCode
- 完善 BusinessException
当有异常进来,会根据错误码主动查询对应错误信息。
<?php
namespace App\Exception;
use Hyperf\Server\Exception\ServerException;
use App\Constants\ErrorCode;
use throwable;
class BusinessException extends ServerException
{
public function __construct(int $code = 0 , string $message = null , throwable $exception = null)
{
if(is_null($message)){
$message = ErrorCode::getMessage($code);
}
parent::__construct($message, $code, $exception);
}
}
三、模型创建
- 命令行创建模型
php bin/hyperf.php gen:model UserModel
php bin/hyperf.php gen:model SongsModel
- 完善模型
class User extends Model
{
protected $table = 'users';
protected $fillable = ['nickname' , 'email' , 'phone_num' , 'password' , 'pic'];
protected $casts = ['id' => 'integer' , 'nickname' => 'string' , 'email' => 'string' , 'phone_num' => 'string' , 'password' => 'string' , 'pic' => 'string'];
}
class Song extends Model
{
protected $table = 'songs';
protected $fillable = ['name' , 'artist' , 'url'];
protected $casts = ['id' => 'integer' , 'artist' => 'string' , 'url' => 'string'];
}