首先新建一个任意名称的控制器文件, 我这里就叫Good.php了
公共函数: 所有公共函数在 app\Helper\Functions.php
// 公共函数测试
function getsi(int $i ,string $b): stdClass
{
$c = new stdClass();
{
$c->id = $i;
$c->body = $b;
}
return $c;
}
手动注解 , 生成一个 http://xxx.com/goodlist 的路由 , 方法时Get
get("id",0);
return getsi($id,"碎笔发布");
}
/**
* request获取参数 post
* @RequestMapping("/goodlist3",method={"POST"})
*/
public function list3(\Swoft\Http\Message\Request $request)
{
$id = $request->post("id",10);
return $id;
}
/**
* request获取请求方式
* @RequestMapping("/go",method={"GET","POST"})
*/
public function methods(\Swoft\Http\Message\Request $request)
{
// 获取任何一种参数
$id = $request->input("id",10);
// 获取请求方式
$method = $request->getMethod();
if ($request->isGet()){
return [$method ,"get请求",$id];
}elseif ($request->isPost()){
return [$method ,"post请求",$id];
}
return [$method,$id];
}
}
/**
* request获取请求方式
* @RequestMapping("/go",method={"GET","POST"})
*/
public function methods(\Swoft\Http\Message\Request $request)
{
// 请求上下文保存数据
Context::get()->set("user","zhuzhuxia");
// 请求上下文获取数据
echo Context::get()->get("user");
// 请求上下文保存数据
Context::get()->setMulti(["users"=>["id"=>123,"name"=>"zhuzhuxia"]]);
// 请求上下文获取数据
print_r( Context::get()->getData());
// 请求上下文获取请求GET数据
$ids = Context::get()->getRequest()->get("ids",55);
// 请求上下文获取请求POST数据
$id = Context::get()->getRequest()->post("id",55);
// 请求上下文获取请求方式
$method = Context::get()->getRequest()->getMethod();
return [$ids , $id ,$method];
}
HTTP Server | Swoft基于 \Swoole\Http\Server 实现的协程 HTTP 服务, 框架层做了很好的封装, 用户按照传统的 MVC 方式编写代码, 就能获得协程带来的超高性能.安装 Composer 安装 composer require swoft/http-server Git 仓库 Github https://github.com/swoft-cloud/swoft-http-server 参与贡献 欢迎参与贡献,您可以 fork 我们的开发仓库 swoft/component 修改代码然后发起 PR 阅读 提交代码 的注意事项 功能特色 基于 PSR-7 的 HTTP 消息实现 基于 PSR-15 的中间件 @Controller 灵活的控制器注解 @RequestMapping 灵活的路由注解 Http 生命周期 了解请求生命周期, 有利于理解HTTP服务各组件, 编写出更好代码. 请求处理流程 Http Server 命令 $php bin/swoft http Provide some commands to manage the swoft HTTP server Group: http (alias: httpsrv) Usage: bin/swoft http:COMMAND [--opt .https://www.swoft.org/documents/v2/core-components/http-server/#%E4%B8%AD%E9%97%B4%E4%BB%B6
/**
* Class DomainLimitMiddleware
*
* @Bean()
*/
class DomainLimitMiddleware implements MiddlewareInterface
{
}
在类或者方法上使用@Middleware()
use App\Http\Middleware\DomainLimitMiddleware;
/**
* @Controller()
* @Middleware(DomainLimitMiddleware::class)
*/
class Good
{
}
use App\Http\Middleware\ApiMiddleware;
use App\Http\Middleware\ControllerMiddleware;
/**
* @Controller()
* @Middlewares({
* @Middleware(ApiMiddleware::class),
* @Middleware(ControllerMiddleware::class)
* })
*/
class Good
{
}
只需在 Bean
配置文件内配置 httpDispatcher
的 middlewares
属性,在数组中加入你的自定义中间件的命名空间地址,相关配置通常在 app/bean.php
内。
return [
...
'httpDispatcher'=>[
'middlewares'=>[
AuthMiddleware::class,
ApiMiddleware::class
]
]
...
]