PHP code example of jokerng / hyperf-demo

1. Go to this page and download the library: Download jokerng/hyperf-demo 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/ */

    

jokerng / hyperf-demo example snippets


namespace App\Controller;

use App\Trait\ResponseTrait;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Controller('/api')]
class UserController
{
    use ResponseTrait;

    #[RequestMapping(path: '/info', methods: ['get'])]
    public function info()
    {
        // 成功响应
        return $this->success(['id' => 1, 'name' => 'hyperf']);

        // 失败响应
        return $this->error('参数错误', 400);
    }
}

use App\Exception\AppException;

throw new AppException('用户不存在', 10004);

return [
    'http' => [
        App\Middleware\CorsMiddleware::class,
        App\Middleware\CleanXssMiddleware::class,
        ValidationMiddleware::class,
    ],
];

use App\Service\SmCryptorService;

class IndexController extends AbstractController
{
    public function __construct(protected SmCryptorService $smCryptor)
    {
    }

    public function encrypt()
    {
        $cipher = $this->smCryptor->sm4Encrypt('hello');
        return $this->success(['cipher' => $cipher]);
    }
}

use App\Service\WechatService;

class IndexController extends AbstractController
{
    public function __construct(protected WechatService $wechatService)
    {
    }

    public function getUserInfo(string $openId)
    {
        $app = $this->wechatService->officialAccount();
        $user = $app->getUser()->get($openId);
        return $this->success($user);
    }
}

use App\Service\JwtService;

class AuthController extends AbstractController
{
    public function __construct(protected JwtService $jwtService)
    {
    }

    public function login(int $userId)
    {
        return $this->success([
            'access_token' => $this->jwtService->generateAccessToken($userId),
            'refresh_token' => $this->jwtService->generateRefreshToken($userId),
            'expires_in' => $this->jwtService->getAccessTtl(),
        ]);
    }

    public function logout(string $token)
    {
        $this->jwtService->addToBlacklist($token, $this->jwtService->getRemainingTtl($token));
        return $this->success(message: '注销成功');
    }
}

use Hyperf\Context\Context;
use App\Middleware\AuthMiddleware;

$userId = Context::get(AuthMiddleware::AUTH_USER_ID);

// config/routes.php
use App\Middleware\AuthMiddleware;

Router::addRoute(['GET', 'POST'], '/user/profile', 'App\Controller\UserController@profile', [
    'middleware' => [AuthMiddleware::class],
]);
bash
cd path/to/install
php bin/hyperf.php start

[2025-01-15 10:30:25] hyperf.INFO: Request started {"request_id":"679758...","method":"POST","uri":"/api/login","body":{"username":"admin"},"client_ip":"192.168.1.100"}
[2025-01-15 10:30:25] hyperf.INFO: Request completed {"request_id":"679758...","status_code":200,"duration_ms":45.23,"client_ip":"192.168.1.100"}
bash
# 启动开发服务器
php bin/hyperf.php start

# 运行测试
composer test

# 代码格式化
composer cs-fix

# 静态分析
composer analyse

# 清理代理缓存(热更新异常时可执行)
composer start