swoft學習筆記之request請求

獲取 request 對象

  • 通過控制方法參數注入的方式
<?php declare(strict_types=1);
    
    namespace app\Http\Controller;
    
    use Swoft\Http\Message\Request;
    
    class TestController{
        
        public  function create(Request $request)
        {
            
        }
    }
  • 通過請求上下文獲取
<?php declare(strict_types=1);
    
    namespace app\Http\Controller;
    
    use Swoft\Context\Context;
    
    class TestController{
    
        protected $request;
        
        public function __construct(){
            $this->request = Context::mustGet()->getRequest();
        }
        
        public  function create()
        {
            $params = $this->request->input();
            //TODO  SOMETHING
        }
    }

獲取請求數據

在介紹獲取請求數據之前,我們先看一下源碼,文件路徑爲 vendor/swoft/http-message/src/Request.php

    class Request extends PsrRequest implements ServerRequestInterface
    {
        use InteractsWithInput;
    
        .
        .
        .
    
    }

可見 Request 類繼承了 PsrRequest 類,實現了 ServerRequestInterface 接口,並引用了 InteractsWithInput trait。

獲取請求 method
    $method = $request->getMethod();
獲取請求的 uri
    $uri        = $request->getUri();//該方法返回的是對象,是對象,是對象
    $scheme     = $uri->getScheme();
    $authority  = $uri->getAuthority();
    $userInfo   = $uri->getUserInfo();
    $host       = $uri->getHost();
    $port       = $uri->getPort();
    $path       = $uri->getPath();
    $query      = $uri->getQuery();
    $fragment   = $uri->getFragment();
獲取請求 headers
	// 獲取全部header
    $headers = $request->getHeaders();

	// 獲取單個header
    $host = $headers = $request->getHeader('host'); //返回值是array
    $host = $request->getHeaderLine("host");//返回值是字符串
獲取 get 數據
    $data = $request->query();
    $some = $request->query('key', 'default value')
    //推薦使用get
    $data = $request->get();
    $some = $request->get('key','default value');
獲取 post 數據
    $data = $request->post();
    $some = $request->post('key', 'default value')
獲取 get & post 數據
    $data = $request->input();
    $some = $request->input('key', 'default value')
獲取上傳文件
    $file = $request->getUploadedFiles();//獲取的結果是一維數組或者二位數組
    //數組內容是 Swoft\Http\Message\Upload\UploadedFile 文件對象,對象,對象
    /**
    *文件操作方法
     moveTo() 將上傳的文件移動到新位置。
     getSize() 獲取文件大小,單位 byte。
     getError() 獲取上傳文件相關的錯誤信息,若無錯將必須返回UPLOAD_ERR_OK 常量,若又錯誤將返回UPLOAD_ERR_XXX 相關常量。
     getClientFilename() 獲取文件上傳時客戶端本地的文件名,不要相信此方法返回的值。客戶端可能會發送惡意虛假文件名,意圖破壞或破解您的應用程序。
     getClientMediaType() 獲取客戶端中文件的 MediaType 類型,不要相信此方法返回的值。客戶端可能會發送惡意虛假文件名,意圖破壞或破解您的應用程序。
    */
其它一些方法

其他方法請查看源碼或者官方文檔

    if ($request->isAjax()) {
        // Do something
    }
    if ($request->isGet()) {
        // Do something
    }
    $contentType = $request->getContentType();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章