响应对象 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
<?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");
$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]