swoft微服务实战十四:获取Http响应对象方式

本文详细介绍了在Swoft框架中如何获取HTTP响应对象,包括通过控制器方法参数注入和请求上下文获取。同时讨论了RequestMapping的原码和Context上下文对象的使用,以及如何返回JSON格式的内容。
摘要由CSDN通过智能技术生成

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函数中.
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值