扩展easysms来实现发送验证码

发送注册验证码,在发送的时候注入RegisgetrMessage,这样找回密码的时候就容易扩展了

public function register(RegisterVerificationCodeRequest $request): JsonResponse
{
    $phone = $request->phone;
    $code = $this->verificationCodeService->getVerificationCode();
    return response()->json($this->verificationCodeService->send($phone, new RegisterMessage($code)))->setStatusCode(201);
}

在RegisterMessage中实现自定义接口VerificationCodeMessageInterface

interface VerificationCodeMessageInterface
{
    public function getCode();
}
class RegisterMessage extends Message implements VerificationCodeMessageInterface
{

    public function __construct($code)
    {
        $this->code = $code;
    }
    //其它更多代码
// getCode在接口中定义
     public function getCode() {
         return $this->code;
     }
    }
class VerificationCodeService
{
    public function send($phone, Message $verificationCodeMessage): array
    {
        if(! ($verificationCodeMessage instanceof VerificationCodeMessageInterface))
        {
            //VerificationCodeMessageInterface接口也可以实现自Easysms中定义的Overtrue\EasySms\Contracts\MessageInterface,然后此方法传参的时候使用VerificationCodeMessageInterface修饰$verificationCodeMessage,你们觉得那种方法更合适
            throw new \Exception(sprintf('消息对象必须实现接口 %s', VerificationCodeMessageInterface::class));
        }

        if(App::environment('production')) {
            try {
                $result = app('easysms')->send($phone, $verificationCodeMessage);
            }catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
                $message = $exception->getLastException()->getMessage();
                abort(500, $message);
            }
        }

        $code = $verificationCodeMessage->getCode();
        $key = Str::random(15);
        $cacheKey = 'verification_code_'.$key;
        $expiredAt = now()->addMinutes(10);
        Cache::put($cacheKey, ['phone' => $phone, 'code' => $code], $expiredAt);

        return [
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ];
    }

    public function getVerificationCode(): string
    {
        if (App::environment('production')) {
           return str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        }else {
            return '1234';
        }
    }
}
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
if(! ($verificationCodeMessage instanceof VerificationCodeMessageInterface))
{
    throw new \Exception(sprintf('消息对象必须实现接口 %s', VerificationCodeMessageInterface::class));
}

这段感觉VerificationCodeMessageInterface也可以直接继承自他的接口,然后在调用的时候直接用此接口限制,但是他的内置Message也实现了他的自己的接口,这样相当于接口里面的方法定义是有重复了,你们觉得那种方式合理

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!