PHP code example of yhs / hyperf-scaffold

1. Go to this page and download the library: Download yhs/hyperf-scaffold library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yhs / hyperf-scaffold example snippets




declare(strict_types=1);

namespace App\Constants;

class UriConstant
{
    /**
     * 版本
     */
    public const VERSION = 'v1';
    /**
     * 首页前缀
     */
    public const INDEX_PREFIX = 'index';

    private function __construct()
    {
    }
}



declare(strict_types=1);


namespace App\Controller;

use App\Constants\CommonConstant;
use App\Constants\UriConstant;
use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\POJO\VO\Response\UserLoginResponseVO;
use App\Service\UserService;
use App\Utils\LogUtil;
use App\Utils\Stopwatch;
use Hyperf\ApiDocs\Annotation\Api;
use Hyperf\ApiDocs\Annotation\ApiHeader;
use Hyperf\ApiDocs\Annotation\ApiOperation;
use Hyperf\ApiDocs\Annotation\ApiResponse;
use Hyperf\Di\Annotation\Inject;
use Hyperf\DTO\Annotation\Contracts\RequestBody;
use Hyperf\DTO\Annotation\Contracts\Valid;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

#[Api(tags: '用户中心接口', description: '用户中心接口包含:用户中心收获地址、获取用户信息、登录、退出、注册')]
#[ApiHeader(name: 'Authorization', $stopwatch = new Stopwatch();
        $businessResponse = $this->userService->login($userLoginRequestVO);
        $this->logger->info("response user login api result: {$businessResponse}");
        $this->logger->info("response user login api cost: {$stopwatch->elapsed(CommonConstant::THREE)}ms");

        return $this->response->json($businessResponse->toArray());
    }
}
 $this->response->json() 
 businessResponse = $this->userService->login($userLoginRequestVO); 



declare(strict_types=1);


namespace App\Enum;

use App\Common\BusinessResult;
use App\POJO\BusinessResponse;

enum UserResponseEnum
{
    case ERROR_LOGIN_TYPE;
    case AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY;
    case ACCOUNT_IS_EMPTY;
    case ERROR_LOGIN_ACCOUNT_TYPE;
    case PASSWORD_IS_EMPTY;
    case CAPTCHA_IS_EMPTY;

    public function response(): BusinessResponse
    {
        return match ($this) {
            self::ERROR_LOGIN_TYPE => BusinessResult::fail(50001, '登录类型错误!'),
            self::AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY => BusinessResult::fail(50002, '自动登录密文不能为空!'),
            self::ACCOUNT_IS_EMPTY => BusinessResult::fail(50003, '登录账号不能为空!'),
            self::ERROR_LOGIN_ACCOUNT_TYPE => BusinessResult::fail(50004, '错误账号登录类型!'),
            self::PASSWORD_IS_EMPTY => BusinessResult::fail(50005, '登录密码不能为空!'),
            self::CAPTCHA_IS_EMPTY => BusinessResult::fail(50006, '验证码不能为空!'),
        };
    }
}

 UserLoginRequestVO.php 



declare(strict_types=1);


namespace App\Service\Impl;

use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\Service\Impl\Logic\LoginLogic;
use App\Service\Impl\Verification\LoginVerification;
use App\Service\UserService;
use App\Utils\LogUtil;
use Hyperf\Di\Annotation\Inject;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class UserServiceImpl implements UserService
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(UserServiceImpl::class);
    }

    /**
     * @var LoginVerification 检查用户登录参数
     */
    #[Inject]
    protected LoginVerification $loginVerification;

    /**
     * @var LoginLogic 登录逻辑
     */
    #[Inject]
    protected LoginLogic $loginLogic;

    /**
     * 登录
     *
     * @param UserLoginRequestVO $userLoginRequestVO
     * @return BusinessResponse
     */
    public function login(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('start user login service.');

        // 校验参数
        $checkParameter = $this->loginVerification->check($userLoginRequestVO);
        if(!$checkParameter->isSuccess())
        {
            return $checkParameter;
        }

        // 登录逻辑
        return $this->loginLogic->exec($userLoginRequestVO);
    }
}

    /**
     * @var LoginVerification 检查用户登录参数
     */
    #[Inject]
    protected LoginVerification $loginVerification;

    /**
     * @var LoginLogic 登录逻辑
     */
    #[Inject]
    protected LoginLogic $loginLogic;



declare(strict_types=1);


namespace App\Service\Impl\Verification;

use App\Common\BusinessResult;
use App\Constants\LoginTypeConstant;
use App\Enum\UserResponseEnum;
use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\Utils\LogUtil;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class LoginVerification
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(LoginVerification::class);
    }

    /**
     * 检查用户登录参数
     *
     * @param UserLoginRequestVO $userLoginRequestVO 用户登录的参数
     * @return BusinessResponse
     */
    public function check(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('check user login parameters verification.');

        // 根据登录类型判断参数
        switch ($userLoginRequestVO->getLoginType())
        {
            case LoginTypeConstant::ACCOUNT:
                // 判断账号是否为空
                if(empty($userLoginRequestVO->getAccount())) {
                    return BusinessResult::failForEnum(UserResponseEnum::ACCOUNT_IS_EMPTY->response());
                }
                // 判断密码是否为空
                if (empty($userLoginRequestVO->getPassword())) {
                    return BusinessResult::failForEnum(UserResponseEnum::PASSWORD_IS_EMPTY->response());
                }
                break;
            case LoginTypeConstant::CAPTCHA:
                // 判断账号是否为空
                if(empty($userLoginRequestVO->getAccount())) {
                    return BusinessResult::failForEnum(UserResponseEnum::ACCOUNT_IS_EMPTY->response());
                }
                // 判断密码是否为空
                if (empty($userLoginRequestVO->getCaptcha())) {
                    return BusinessResult::failForEnum(UserResponseEnum::CAPTCHA_IS_EMPTY->response());
                }
                break;
            case LoginTypeConstant::AUTO_LOGIN:
                // 判断自动登录token是否为空
                if(empty($userLoginRequestVO->getAutomaticLoginToken())) {
                    return BusinessResult::failForEnum(UserResponseEnum::AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY->response());
                }
                break;
            default:
                return BusinessResult::failForEnum(UserResponseEnum::ERROR_LOGIN_TYPE->response());
        }

        // 返回
        return BusinessResult::ok(null);
    }
}



declare(strict_types=1);


namespace App\Service\Impl\Logic;

use App\Common\BusinessResult;
use App\Constants\CommonConstant;
use App\Enum\CallbackEnum;
use App\Model\UserModel;
use App\POJO\BusinessResponse;
use App\POJO\PO\UserPO;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\POJO\VO\Response\UserLoginResponseVO;
use App\Utils\LocalDateTime;
use App\Utils\LogUtil;
use Hyperf\DbConnection\Db;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class LoginLogic
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(LoginLogic::class);
    }

    /**
     * 登录逻辑
     *
     * @param UserLoginRequestVO $userLoginRequestVO 用户登录参数
     * @return BusinessResponse
     */
    public function exec(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('start exec user login logic.');

        // 登录
        $expire = LocalDateTime::plusHour(CommonConstant::FOUR);
        $userLoginResponse = new UserLoginResponseVO();
        $userLoginResponse->setToken('token'); // 模拟返回token
        $userLoginResponse->setLoginTime(LocalDateTime::now()); // 模拟返回登录时间
        $userLoginResponse->setExpireTime(LocalDateTime::plusHour(CommonConstant::FOUR)); // 模拟返回过期时间
        $userLoginResponse->setExpire(LocalDateTime::timestampForSecond($expire)); // 模拟返回过期时间

        // 查数据库,同时将查询的数据返回给UserPO对象
        $userList = UserModel::query()->get()->map(CallbackEnum::MODEL_MAP_CALLBACK->callback(UserPO::class));
        var_dump($userList);

        return BusinessResult::ok($userLoginResponse);
    }
}



namespace App\Enum;

use App\Constants\CommonConstant;
use ReflectionClass;

enum CallbackEnum
{
    /**
     * 数据库查询结果反射到对象  查询数据时使用map()操作,案例:Model::query()->get()->map(CallbackEnum::MODEL_MAP_CALLBACK->callback(OrderPO::class));
     */
    case MODEL_MAP_CALLBACK;

    public function callback(?string $className = null): callable
    {
        return match ($this) {
            self::MODEL_MAP_CALLBACK => function ($value) use ($className) {
                // 获取赋值的对象名
                $className = $className ?? $value->className;

                // 判断是否存在对象
                if (empty($className) || !class_exists($className)) {
                    return $value;
                }

                // 初始化一个对象
                $objectClass = new $className();
                $reflectionClass = new ReflectionClass($objectClass);

                // 将查询结果转数组进行反射
                foreach ($value->toArray() as $k => $v) {
                    // 过滤空值
                    if (null == $v) {
                        continue;
                    }

                    // 已"_"下划线进行分割
                    $parts = explode(CommonConstant::SYMBOL_UNDERSCORE, $k);
                    // 拼接方法
                    $propertyName = 'set' . implode(CommonConstant::EMPTY, array_map('ucfirst', $parts));
                    // 判断对象中的方法是否存在
                    if ($reflectionClass->hasMethod($propertyName)) {
                        $reflectionProperty = $reflectionClass->getMethod($propertyName);
                        $reflectionProperty->invoke($objectClass, $v);
                    }
                }
                // 返回对象结果
                return $objectClass;
            },
        };
    }
}

 LocalDateTime.php 
 LogUtil.php 
 Stopwatch.php 
 ToolsUtil.php 
 SeataUtil.php 



declare(strict_types=1);


namespace App\Controller;

use App\Constants\CommonConstant;
use App\Constants\UriConstant;
use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\POJO\VO\Response\UserLoginResponseVO;
use App\Service\UserService;
use App\Utils\LogUtil;
use App\Utils\Stopwatch;
use Hyperf\ApiDocs\Annotation\Api;
use Hyperf\ApiDocs\Annotation\ApiHeader;
use Hyperf\ApiDocs\Annotation\ApiOperation;
use Hyperf\ApiDocs\Annotation\ApiResponse;
use Hyperf\Di\Annotation\Inject;
use Hyperf\DTO\Annotation\Contracts\RequestBody;
use Hyperf\DTO\Annotation\Contracts\Valid;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;

#[Api(tags: '用户中心接口', description: '用户中心接口包含:用户中心收获地址、获取用户信息、登录、退出、注册')]
#[ApiHeader(name: 'Authorization', $stopwatch = new Stopwatch();
        $businessResponse = $this->userService->login($userLoginRequestVO);
        $this->logger->info("response user login api result: {$businessResponse}");
        $this->logger->info("response user login api cost: {$stopwatch->elapsed(CommonConstant::THREE)}ms");

        return $this->response->json($businessResponse->toArray());
    }
}



declare(strict_types=1);


namespace App\Constants;

class UriConstant
{
    /**
     * 版本
     */
    public const VERSION = 'v1';
    /**
     * 首页前缀
     */
    public const INDEX_PREFIX = 'index';

    private function __construct()
    {
    }
}



namespace App\Enum;

use App\Constants\CommonConstant;
use ReflectionClass;

enum CallbackEnum
{
    /**
     * 数据库查询结果反射到对象  查询数据时使用map()操作,案例:Model::query()->get()->map(CallbackEnum::MODEL_MAP_CALLBACK->callback(OrderPO::class));
     */
    case MODEL_MAP_CALLBACK;

    public function callback(?string $className = null): callable
    {
        return match ($this) {
            self::MODEL_MAP_CALLBACK => function ($value) use ($className) {
                // 获取赋值的对象名
                $className = $className ?? $value->className;

                // 判断是否存在对象
                if (empty($className) || !class_exists($className)) {
                    return $value;
                }

                // 初始化一个对象
                $objectClass = new $className();
                $reflectionClass = new ReflectionClass($objectClass);

                // 将查询结果转数组进行反射
                foreach ($value->toArray() as $k => $v) {
                    // 过滤空值
                    if (null == $v) {
                        continue;
                    }

                    // 已"_"下划线进行分割
                    $parts = explode(CommonConstant::SYMBOL_UNDERSCORE, $k);
                    // 拼接方法
                    $propertyName = 'set' . implode(CommonConstant::EMPTY, array_map('ucfirst', $parts));
                    // 判断对象中的方法是否存在
                    if ($reflectionClass->hasMethod($propertyName)) {
                        $reflectionProperty = $reflectionClass->getMethod($propertyName);
                        $reflectionProperty->invoke($objectClass, $v);
                    }
                }
                // 返回对象结果
                return $objectClass;
            },
        };
    }
}




declare(strict_types=1);


namespace App\Enum;

use App\Common\BusinessResult;
use App\POJO\BusinessResponse;

enum UserResponseEnum
{
    case ERROR_LOGIN_TYPE;
    case AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY;
    case ACCOUNT_IS_EMPTY;
    case ERROR_LOGIN_ACCOUNT_TYPE;
    case PASSWORD_IS_EMPTY;
    case CAPTCHA_IS_EMPTY;

    public function response(): BusinessResponse
    {
        return match ($this) {
            self::ERROR_LOGIN_TYPE => BusinessResult::fail(50001, '登录类型错误!'),
            self::AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY => BusinessResult::fail(50002, '自动登录密文不能为空!'),
            self::ACCOUNT_IS_EMPTY => BusinessResult::fail(50003, '登录账号不能为空!'),
            self::ERROR_LOGIN_ACCOUNT_TYPE => BusinessResult::fail(50004, '错误账号登录类型!'),
            self::PASSWORD_IS_EMPTY => BusinessResult::fail(50005, '登录密码不能为空!'),
            self::CAPTCHA_IS_EMPTY => BusinessResult::fail(50006, '验证码不能为空!'),
        };
    }
}




declare(strict_types=1);


namespace App\Service\Impl;

use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\Service\Impl\Logic\LoginLogic;
use App\Service\Impl\Verification\LoginVerification;
use App\Service\UserService;
use App\Utils\LogUtil;
use Hyperf\Di\Annotation\Inject;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class UserServiceImpl implements UserService
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(UserServiceImpl::class);
    }

    /**
     * @var LoginVerification 检查用户登录参数
     */
    #[Inject]
    protected LoginVerification $loginVerification;

    /**
     * @var LoginLogic 登录逻辑
     */
    #[Inject]
    protected LoginLogic $loginLogic;

    /**
     * 登录
     *
     * @param UserLoginRequestVO $userLoginRequestVO
     * @return BusinessResponse
     */
    public function login(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('start user login service.');

        // 校验参数
        $checkParameter = $this->loginVerification->check($userLoginRequestVO);
        if(!$checkParameter->isSuccess())
        {
            return $checkParameter;
        }

        // 登录逻辑
        return $this->loginLogic->exec($userLoginRequestVO);
    }
}



declare(strict_types=1);


namespace App\Service\Impl\Verification;

use App\Common\BusinessResult;
use App\Constants\LoginTypeConstant;
use App\Enum\UserResponseEnum;
use App\POJO\BusinessResponse;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\Utils\LogUtil;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class LoginVerification
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(LoginVerification::class);
    }

    /**
     * 检查用户登录参数
     *
     * @param UserLoginRequestVO $userLoginRequestVO 用户登录的参数
     * @return BusinessResponse
     */
    public function check(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('check user login parameters verification.');

        // 根据登录类型判断参数
        switch ($userLoginRequestVO->getLoginType())
        {
            case LoginTypeConstant::ACCOUNT:
                // 判断账号是否为空
                if(empty($userLoginRequestVO->getAccount())) {
                    return BusinessResult::failForEnum(UserResponseEnum::ACCOUNT_IS_EMPTY->response());
                }
                // 判断密码是否为空
                if (empty($userLoginRequestVO->getPassword())) {
                    return BusinessResult::failForEnum(UserResponseEnum::PASSWORD_IS_EMPTY->response());
                }
                break;
            case LoginTypeConstant::CAPTCHA:
                // 判断账号是否为空
                if(empty($userLoginRequestVO->getAccount())) {
                    return BusinessResult::failForEnum(UserResponseEnum::ACCOUNT_IS_EMPTY->response());
                }
                // 判断密码是否为空
                if (empty($userLoginRequestVO->getCaptcha())) {
                    return BusinessResult::failForEnum(UserResponseEnum::CAPTCHA_IS_EMPTY->response());
                }
                break;
            case LoginTypeConstant::AUTO_LOGIN:
                // 判断自动登录token是否为空
                if(empty($userLoginRequestVO->getAutomaticLoginToken())) {
                    return BusinessResult::failForEnum(UserResponseEnum::AUTOMATIC_LOGIN_CIPHERTEXT_IS_EMPTY->response());
                }
                break;
            default:
                return BusinessResult::failForEnum(UserResponseEnum::ERROR_LOGIN_TYPE->response());
        }

        // 返回
        return BusinessResult::ok(null);
    }
}



declare(strict_types=1);


namespace App\Service\Impl\Logic;

use App\Common\BusinessResult;
use App\Constants\CommonConstant;
use App\Enum\CallbackEnum;
use App\Model\UserModel;
use App\POJO\BusinessResponse;
use App\POJO\PO\UserPO;
use App\POJO\VO\Request\UserLoginRequestVO;
use App\POJO\VO\Response\UserLoginResponseVO;
use App\Utils\LocalDateTime;
use App\Utils\LogUtil;
use Hyperf\DbConnection\Db;
use HyperfHelper\Dependency\Annotation\Dependency;
use Psr\Log\LoggerInterface;

#[Dependency]
class LoginLogic
{
    /**
     * @var LoggerInterface 日志
     */
    private LoggerInterface $logger;

    public function __construct()
    {
        $this->logger = LogUtil::get(LoginLogic::class);
    }

    /**
     * 登录逻辑
     *
     * @param UserLoginRequestVO $userLoginRequestVO 用户登录参数
     * @return BusinessResponse
     */
    public function exec(UserLoginRequestVO $userLoginRequestVO): BusinessResponse
    {
        $this->logger->info('start exec user login logic.');

        // 登录
        $expire = LocalDateTime::plusHour(CommonConstant::FOUR);
        $userLoginResponse = new UserLoginResponseVO();
        $userLoginResponse->setToken('token'); // 模拟返回token
        $userLoginResponse->setLoginTime(LocalDateTime::now()); // 模拟返回登录时间
        $userLoginResponse->setExpireTime(LocalDateTime::plusHour(CommonConstant::FOUR)); // 模拟返回过期时间
        $userLoginResponse->setExpire(LocalDateTime::timestampForSecond($expire)); // 模拟返回过期时间

        // 查数据库,同时将查询的数据返回给UserPO对象
        $userList = UserModel::query()->get()->map(CallbackEnum::MODEL_MAP_CALLBACK->callback(UserPO::class));
        var_dump($userList);

        return BusinessResult::ok($userLoginResponse);
    }
}