swoft 學習筆記之 response 篇

zs4336發表於2019-08-12

一、響應物件 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 的獲取

  • 通過控制器方法注入
  • 通過請求上下文獲取

    <?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 狀態碼的意義。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

趁還沒掉光,趕緊給每根頭髮起個名字吧~

相關文章