3. RestApi:
前后分离、异构系统之间(java、php、go多种混合语言一起开发)、服务和服务之间通常使用api的方式进行互通.
api可以使用http api、RPC api进行交互.
3.1 Http api:
因为到时会部署多台docker api互通,不是所有功能都会使用.下面来精简一下目录结构:
app
├─ Exception // 保留整个文件夹
│ └─ Handler
├─ Helper // 保留整个文件夹
├─ Http
│ ├─ Controller // 里面除了HomeController全部删除
│ │ └─ HomeController
│ └─ Middleware // 保留整个文件夹
├─ Application.php
├─ AutoLoader.php
└─ bean.php
3.2 RPC:
实际开发中,大多数是RPC的方式来调用.
4. 全局函数:
在整体框架启动后,直接会加载Function.
在Swoft中可以使用@Controller()和@RequestMapping注解快速的添加路由.
<?php declare(strict_types=1);
namespace App\Http\Controller;
use Swoft\Context\Context;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
/**
* @Controller() // 表示是一个控制器
*/
class Product
{
/**
* @RequestMapping("productList") // 表示映射到哪个请求路径
*/
public function index(): Response
{
// swoft封装好的上下文对象,必须选择Swoft\Context的命名空间
// 请求对象
// $request = Context::mustGet()->getRequest();
// 响应对象
$response = Context::mustGet()->getResponse();
return $response->withContent("abc");
}
}
隐式访问URL:http://127.0.0.1:18306/productList
# 组合1:
@Controller(prefix="/v1/test") // 表示路由要加一个/v1/test的前缀
@RequestMapping(route="productList") // 等价于@RequestMapping("index")
# 显示指定路由前缀访问URL:http://127.0.0.1:18306/v1/test/productList
# 组合2:
use Swoft\Http\Server\Annotation\Mapping\RequestMethod;
@Controller()
@RequestMapping("productList", method={RequestMethod::GET}) // 第二个参数表示允许访问的方式
# 这里method的{}表示是一个数组传入,并不是对象,仿java写法
# 显示指定路由前缀访问URL:http://127.0.0.1:18306/productList
# 组合3:
@Controller(prefix="product") // 等价于@Controller(prefix="/product")
@RequestMapping(route="/product") // 前缀与路由一样,会覆盖
# 显示指定路由前缀访问URL:http://127.0.0.1:18306/product
# 如果route没有/,表示访问URL:http://127.0.0.1:18306/product/product
注:
①. 主要通过@controller定义前缀,@RequestMapping定义后缀.
②. @Controller:类注解设置在Controller类上,标记当前类是一个http控制器类.
③. 返回结果:
HTTP/1.1 200 OK
content-type: text/html; charset=utf-8 // content-type为text/html
Server: swoole-http-server
...
④. 安装PHP自动注释支持插件:
phpstrom中打开Settings -> Plugin,安装PHP Annotation