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