当前位置: 首页 > 工具软件 > Swoft > 使用案例 >

swoft response

文彭祖
2023-12-01

响应对象 response

响应对象 Response 为 Swoft\Http\Message\Response

查看 response 对象源码,文件路径为 vendor/swoft/http-message/src/Response.php

class Response implements ResponseInterface
{
    use CookiesTrait, MessageTrait, PrototypeTrait;
    
    .
    .
    .
}

可知 response 对象实现了 ResponseInterface 接口,另外引用 CookiesTrait, MessageTrait, PrototypeTrait 三个trait

响应对象 response 的获取

  1. 通过控制器方法注入
  2. 通过请求上下文获取
<?php declare(strict_types=1);

namespace App\Http\Controller;

use Swoft\Context\Context;
use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Request;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;

/**
 * Class TestController
 * @package App\Http\Controller
 * @Controller(prefix="test")
 */
class TestController
{
    /**
     * @RequestMapping(route="index")
     * @param Request $request
     * @return Response
     */
    public function index(Request $request) : Response
    {
        $path    = $request->getUriPath();
        $headers = $request->getHeaders();

        $data    = [
            'path'    => $path,
            'headers' => $headers,
        ];

        $headers = [
            'token' => 'akdhfheiwoadskajkdjoihh=ahdiu0-2hds',
        ];
        $response = Context::mustGet()->getResponse();
        return $response->withStatus(200)
            ->withContentType(ContentType::JSON)
            ->withHeaders($headers)
            ->withData($data);
    }

    /**
     * @RequestMapping(route="test")
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    public function test(Request $request,Response $response)
    {
        return $response->withData(['name'=>'swoft']);
    }
}

返回响应信息

设置状态码

 $response = \Swoft\Context\Context::mustGet()->Response();
    return $response->withStatus(403);

输出字符串

return $response->withContent("Hello World");

输出数组

$data = ['name'=>'swoft'];
    return $response->withData($data);

输出头信息

 $headers = ['token'=>'dhsjagfuigfiugu=-dsah=dsaj'];
    return $response->withHeaders($headers);

重定向

  return $response->redirect("http://www.swoft.org",302);

文件下载

 return $response->file(\alias('@runtime/1.zip'), "application/octet-stream");

设置 cookie

    $response = $response->withCookie(’name', 'value');

    $cookies = [
        'key1' => 'value1',
        'key2' => ['value' => 'value2'],
    ];
    $response = $response->withCookies($cookies);

其他方法

还有很多方法,比如设置返回数据 Json 类型等,在这里就不一一罗列了,可以查看源代码或者官方文档查看,另外注意 is 开头的方法,有助于理解标准的 http 状态码的意义。

[swoft学习笔记之response篇][1]

[1][https://blog.csdn.net/zs_4336/article/details/99304109]

 类似资料:

相关阅读

相关文章

相关问答