2.1 获取Http响应对象方式:
Swoft的请求与响应实现于PSR 7规范.请求与响应对象存在于每次HTTP请求.
①. Swoft的Http响应对象:
a. 请求对象Request为Swoft\Http\Message\Request
b. 响应对象Response为Swoft\Http\Message\Response
②. 如何获取:
a. 通过控制器方法参数注入(Response $response) => 下例
b. 通过请求上下文获取context()->getResponse() => 上例
use Swoft\Http\Message\ContentType;
/**
* @RequestMapping(route="productSearch", method={RequestMethod::GET})
*/
public function productSearch(Response $response): Response
{
......
// 可以用框架提供的ContentType类,防止自己写"application/json"写错.
return $response->withContentType(ContentType::JSON)->withData([$data]);
}
注:
①. 不是太推荐这种方式,导致形参的参数会很多.
②. 返回的格式:
HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
Server: swoole-http-server
...
2.2 RequestMapping原码:
vendor\swoft\http-server\src\Annotation\Mapping\RequestMapping.php:
<?php
namespace Swoft\Http\Server\Annotation\Mapping;
use Doctrine\Common\Annotations\Annotation\Required; // 使用的是Doctrine Annotation第三方库
use Doctrine\Common\Annotations\Annotation\Target;
/**
* HTTP action method annotation
*/
class RequestMapping
{
/**
* Action routing path
* @Required()
*/
private $route = '';
/**
* Route name
*/
private $name = '';
/**
* Routing supported HTTP method set
*/
private $method = [RequestMethod::GET, RequestMethod::POST]; // 这里是一个数组
/**
* Routing path params binding. eg. {"id"="\d+"}
*/
private $params = [];
...
}
2.3 Context上下文对象:
/**
* Get context by coID, if not found will throw exception.
* @return ContextInterface|HttpContext|WsMessageContext
* @deprecated Instead of `Context::get()` Or `context()->get()`
*/
public static function mustGet(): ContextInterface
{
$tid = Co::tid(); // 根据当前的协程id获取上下文
if (isset(self::$context[$tid])) {
return self::$context[$tid];
}
throw new ContextException('context information has been lost of the coID: ' . $tid);
}
3. 返回JSON格式:
$response = Context::mustGet()->getResponse();
// 从数据库/redis取出来的数据返回json格式
$data = new \stdClass();
{
$data->id = 1;
$data->title = "PHP入门";
}
// content-type要设置为applicaiotn/json
// 链式写法,withContent()只能以string格式输出.
// return $response->withContentType("application/json")->withContent(json_encode([$data]));
return $response->withContentType("application/json")->withData([$data]);
注:
①. Response类都是把当前对象返回,所以可以使用链式写法.
②. 根据PSR-7对象的不可变性(immutable),所有的with*方法都是克隆对象再返回,必须接收新对象来做进一步处理,或使用链式调用.
③. 为了使业务代码更精简,可以将上述response再次封装到全局Helper函数中.