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);
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);