2、注解
Hyperf 使用注解来定义路由、中间件、控制器等。例如:
php
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
/**
* @Controller
*/
class IndexController
{
/**
* @GetMapping(/)
*/
public function index()
{
return ['message' = 'Hello, Hyperf!'];
}
}
4、中间件
Hyperf 支持中间件,可以在请求处理过程中插入自定义逻辑。例如:
php
use Hyperf\HttpServer\Contract\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class ExampleMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// 在请求处理前执行逻辑
echo Before request handling\n;
$response = $handler-handle($request);
// 在请求处理后执行逻辑
echo After request handling\n;
return $response;
}
}
三、路由与控制器
1、定义路由
Hyperf 支持多种方式定义路由,包括注解、配置文件和代码方式。
使用注解定义路由
php
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
/**
* @Controller
*/
class UserController
{
/**
* @GetMapping(/user)
*/
public function getUser()
{
return ['name' = 'John Doe', 'email' = 'john@65.hk'];
}
}