Hyperf实战项目-music(一)

一、统一响应接口

  1. 新增 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 ,
		]);
	}
}
  1. 将 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;
}
  1. 任意接口进行测试
	public function songs()
    {
		return $this->response->success(1);
    }

二、自定义异常处理

  1. 屏蔽源码异常处理
    找到异常处理配置文件,conf/autoload/exception,注释掉 HttpExceptionHandler
return [
    'handler' => [
        'http' => [
            // Hyperf\HttpServer\Exception\Handler\HttpExceptionHandler::class,
            App\Exception\Handler\AppExceptionHandler::class,
        ],
    ],
];
  1. 创建自定义业务异常处理类
namespace App\Exception;

use Hyperf\Server\Exception\ServerException;

class BusinessException extends ServerException
{
	
}
  1. 修改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;
    }
}

可根据环境判断输出错误信息的详细程度。

  1. 枚举类
composer require hyperf/constants

php bin/hyperf.php gen:constant ErrorCode
  1. 完善 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);
	}
}

三、模型创建

  1. 命令行创建模型
php bin/hyperf.php gen:model UserModel
php bin/hyperf.php gen:model SongsModel
  1. 完善模型
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'];
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值