溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在swoft2中如何配置HTTP Server

發(fā)布時(shí)間:2021-10-11 11:33:54 來源:億速云 閱讀:150 作者:iii 欄目:編程語言

這篇文章主要介紹“在swoft2中如何配置HTTP Server”,在日常操作中,相信很多人在在swoft2中如何配置HTTP Server問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”在swoft2中如何配置HTTP Server”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

配置參數(shù)
在應(yīng)用下的 app/bean.php 配置 server,在這個(gè)文件里,你可以看到 Http Server數(shù)組里面包含了 Http Server 的基本信息。下面列舉了一些簡單的配置,你也可以自由組合同時(shí)提供多種服務(wù)。

'httpServer' => [
 'class' => HttpServer::class,
 'port' => 18306,
 'listener' => [
 'rpc' => bean('rpcServer')
 ],
 'process' => [
 //  'monitor' => bean(MonitorProcess::class)
 //  'crontab' => bean(CrontabProcess::class)
 ],
 'on' => [
 // Enable task must task and finish event
 SwooleEvent::TASK   => bean(TaskListener::class), 
 SwooleEvent::FINISH => bean(FinishListener::class)
 ],
 /* @see HttpServer::$setting */
 'setting' => [
 'task_worker_num' => 12,
 'task_enable_coroutine' => true,
 'worker_num' => 6,
 // Enable Https 這個(gè)是配置https證書的可以不設(shè)置
 'ssl_cert_file' => '/my/certs/2288803_www.domain.com.pem',
 'ssl_key_file' => '/my/certs/2288803_www.domain.com.key',
 ]
 ],
 //Enable Https
 'type' => SWOOLE_SOCK_TCP | SWOOLE_SSL,


配置項(xiàng) http server 除了 class 其他都是 http server 的屬性。
配置介紹
class 指定 Http Server 的處理類
port 指定 Http Server 的端口
listener 指定其他一同啟動(dòng)的服務(wù),添加端口服務(wù)監(jiān)聽,可以多個(gè)。
rpc 啟動(dòng) RPC 服務(wù)
process 啟動(dòng)自定義用戶進(jìn)程
on 配置監(jiān)聽的事件 注冊事件、設(shè)置對應(yīng)事件的處理監(jiān)聽,事件觸發(fā)組件調(diào)用,在任務(wù)里面使用
setting 這里是參考 Swoole Server 配置選項(xiàng)

  • pidFile 設(shè)置進(jìn)程 pid 文件 位置,默認(rèn)值 @runtime/swoft.pid

  • mode 運(yùn)行的模式,參考 Swoole Server 構(gòu)造函數(shù) 第三個(gè)參數(shù)

  • type 指定Socket的類型,支持TCP、UDP、TCP6、UDP6、UnixSocket Stream/Dgram 等 Swoole Server 構(gòu)造函數(shù) 第四個(gè)參數(shù)

  • 啟用 Https 支持 注意: 你必須安裝 OpenSSL 庫,并且確保安裝 swoole 時(shí)是啟用了 ssl 選項(xiàng)的。同時(shí),需要設(shè)置 ‘type’ => SWOOLE_SOCK_TCP | SWOOLE_SSL

Controller 控制器
控制器作為HTTP服務(wù)的核心組件,串接起一次請求的整個(gè)生命周期. 通過 注解 的方式,相較于傳統(tǒng)的 Controller,代碼更簡潔,用戶可以更關(guān)注業(yè)務(wù)邏輯。
創(chuàng)建控制器
主要通過 @Controller 注解實(shí)現(xiàn)。代碼可以放置任意位置,不過為了統(tǒng)一標(biāo)準(zhǔn),建議放在 app/Http/Controller 下

namespace App\Http\Controller;

use Swoft\Http\Message\ContentType;
use Swoft\Http\Message\Response;
use Swoft\Http\Server\Annotation\Mapping\Controller;
use Swoft\Http\Server\Annotation\Mapping\RequestMapping;
use Swoft\View\Annotation\Mapping\View;
use Throwable;

/**
 * Class ViewController
 *
 * @since 2.0
 *
 * @Controller(prefix="view")
 */
class ViewController
{
 /**
     * @RequestMapping("index")
     *
     * @param Response $response
     *
     * @return Response
     */
 public function index(Response $response): Response
 {
        $response = $response->withContent('<html lang="en"><h2>Swoft framework</h2></html>');
        $response = $response->withContentType(ContentType::HTML);
 return $response;
 }
}


代碼分析
@Controller 注解
Http 控制器類注解 @Controller
注解類:Swoft\Http\Server\Annotation\Mapping\Controller

  • 作用范圍:CLASS

  • 擁有屬性:

  • prefix 指定路由前綴

通常僅有 @Controller 是沒有什么效果的,它需要配合接下來的 @RequestMapping 一起才能正確的工作。

路由規(guī)則
顯式指定路由前綴:@Controller(prefix=”/index”) 或 @Controller(“/index”)。
隱式指定路由前綴:@Controller() 默認(rèn)自動(dòng)使用 小駝峰 格式解析 controller class 的名稱。
示例:class IndexController 對應(yīng)路由 /index
一個(gè)完整的路由規(guī)則是通過 @Controller + @RequestMapping 注解實(shí)現(xiàn),通常前者定義前綴,后者定義后綴。關(guān)于 @RequestMapping 注解將在稍后 路由-@RequestMapping 章節(jié)將會(huì)詳細(xì)介紹。

在 Swoft 里不要按照傳統(tǒng)的 fpm 框架繼承父類控制器的成員屬性在其他控制器使用,這種做法是錯(cuò)誤的。
錯(cuò)誤示范:

/**
 * @Controller()
 */
class BaseController
{
 protected $num;
}

/**
 * @Controller(prefix="/v1/index")
 */
class IndexController extends BaseController
{
 /**
     * @RequestMapping(route="index")
     */
 public function index()
 {
        $this->num++;
        echo $this->num."\n";//這里每次訪問輸出的都不一樣
 }
}


此時(shí)每次訪問num數(shù)字都會(huì)增1,這個(gè)是錯(cuò)誤的使用方式,和傳統(tǒng)的 php-fpm 有很大區(qū)別.傳統(tǒng)的 fpm 每次執(zhí)行過后都會(huì)釋放內(nèi)存,而 swoft 是常駐內(nèi)存的 大家一定要注意
路由
Swoft 與傳統(tǒng)的 PHP 框架不一樣,并沒有采用配置文件的方式來配置路由,而采用了注解。在 Swoft 里我們可以使用 @RequestMapping 注解快速的添加路由。
@RequestMapping 注解
Http 控制器類中方法路由注解 @RequestMapping

  • route 路由規(guī)則path

  • method 請求方式(GET、POST、PUT、PATCH、DELETE、OPTIONS、HEAD)

  • params 可以通過它為path變量添加正則匹配限制

每個(gè)方法上盡量只寫一個(gè) @RequestMapping 注解,以免出現(xiàn)紊亂。
路由規(guī)則
通常情況,一個(gè)完整的路由 path 等于 @Controller 的 prefix + @RequestMapping 的 route 顯示指定路由后綴:@RequestMapping(“index”) 或 @RequestMapping(route=”index”)
隱式指定路由后綴: 使用 @RequestMapping() 默認(rèn)解析方法名為后綴
特殊的,當(dāng)你的 @RequestMapping 上的路由以 / 開頭時(shí),那完整的路由就是它,即不會(huì)再將 prefix 添加到它的前面
允許的請求方法為默認(rèn)為 GET 和 POST 當(dāng)設(shè)置跨域是需要手動(dòng)指定允許 OPTIONS
綁定路由 path 參數(shù)
指定路由參數(shù): @RequestMapping(route=”index/{name}”),Action 方法中可以直接使用 $name 作為方法參數(shù)
當(dāng)路由參數(shù)被 [] 包起來則 URL path 傳遞參數(shù)是可選的。注意,可選符只能用在最后面

  • 示例1: @RequestMapping(“/index[/{name}]”) 這樣 /index /index/tom 都可以訪問到

  • 示例2: @RequestMapping(“/about[.html]”) 相當(dāng)于偽靜態(tài),/about /about.html 都可以訪問到

設(shè)置路由請求方式
如果想要設(shè)置允許請求控制器的 HTTP 請求方式。 可以使用方法在控制器中的 @RequestMapping 注解配置 method 參數(shù),可以是 GET、POST、PUT、PATCH、DELETE、OPTIONS、HEAD 中的一個(gè)或多個(gè)。

@RequestMapping(route="index",method={RequestMethod::GET,RequestMethod::POST})


請切記要引入相關(guān)的注解類

Swoft\Http\Server\Annotation\Mapping\RequestMapping
Swoft\Http\Server\Annotation\Mapping\RequestMethod


Http 請求對象
Swoft 的請求與響應(yīng)實(shí)現(xiàn)于 PSR-7 規(guī)范。請求與響應(yīng)對象存在于每次 HTTP 請求。

  • 請求對象 Request 為 Swoft\Http\Message\Request

  • 響應(yīng)對象 Response 為 Swoft\Http\Message\Response

獲取請求對象

$request = context()->getRequest();


示例: 獲取請求的 URI

$uri=$request->getUri();


請求對象的 URI 本身就是一個(gè)對象,它提供了下列方法檢查 HTTP 請求的 URL 部分

$uri->getScheme()

$uri->getAuthority()

$uri->getUserInfo()

$uri->getHost()

$uri->getPort()

$uri->getPath()

$uri->getQuery() (例如 a=1&b=2)

$uri->getFragment()


示例: 獲取請求 Headers
全部的 Headers

$headers = $request->getHeaders();


指定的 Header

$host = $request->getHeaderLine("host");


示例: 獲取請求的數(shù)據(jù)
GET 數(shù)據(jù)

$data = $request->query();

$some = $request->query('key', 'default value')

$data = $request->get();

$some = $request->get('key','default value');


POST 數(shù)據(jù)

$data = $request->post();

$some = $request->post('key', 'default value')


無需關(guān)心請求的數(shù)據(jù)格式,json xml 請求都會(huì)自動(dòng)解析為 php 的數(shù)組數(shù)據(jù)。都可以通過 $request->post() 獲取。
同時(shí)獲取 GET & POST 數(shù)據(jù)

$data = $request->input();

$some = $request->input('key', 'default value')


RAW 數(shù)據(jù)

$data = $request->raw();


SERVER 數(shù)據(jù)

$data = $request->getServerParams();

$some = $request->server('key', 'default value')


獲取上傳文件

$file = $request->getUploadedFiles();


獲取的結(jié)果是一維數(shù)組或者二位數(shù)組,數(shù)據(jù)結(jié)構(gòu)如下。 若表單中上傳的是單文件則返回的是一個(gè)一維數(shù)組,數(shù)組內(nèi)容是 Swoft\Http\Message\Upload\UploadedFile 文件對象,例如文件字段名為 file 則數(shù)據(jù)結(jié)構(gòu)如下
注意這個(gè) UploadedFile 對象的屬性都是私有屬性,withdata過濾了私有屬性所以直接輸出 $file這個(gè)對象輸出的是個(gè)空數(shù)組,而不是上傳未接受到數(shù)據(jù).
獲取的結(jié)果是一維數(shù)組或者二位數(shù)組,數(shù)據(jù)結(jié)構(gòu)如下。 若表單中上傳的是單文件則返回的是一個(gè)一維數(shù)組,數(shù)組內(nèi)容是 Swoft\Http\Message\Upload\UploadedFile 文件對象,例如文件字段名為 file 則數(shù)據(jù)結(jié)構(gòu)如下

array(1) {
 ["file"]=>
 object(Swoft\Http\Message\Upload\UploadedFile)#6510 (7) {
 ["size":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 int(1319)
 ["errorCode":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 int(0)
 ["file":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(25) "/tmp/swoole.upfile.f7p2EL"
 ["clientFilename":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(6) "at.png"
 ["clientMediaType":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(9) "image/png"
 ["moved":"Swoft\Http\Message\Upload\UploadedFile":private]=>
    NULL
 ["path":"Swoft\Http\Message\Upload\UploadedFile":private]=>
    NULL
 }
}


若表單中是一個(gè)字段數(shù)組上傳多個(gè)文件如 file[] 則返回的是一個(gè)二維數(shù)組,數(shù)組內(nèi)容依然是 Swoft\Http\Message\Upload\UploadedFile 文件對象,數(shù)據(jù)結(jié)構(gòu)如下

array(1) {
 ["file"]=>
  array(2) {
 [0]=>
 object(Swoft\Http\Message\Upload\UploadedFile)#6516 (7) {
 ["size":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 int(1319)
 ["errorCode":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 int(0)
 ["file":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(25) "/tmp/swoole.upfile.TVKdOS"
 ["clientFilename":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(6) "at.png"
 ["clientMediaType":"Swoft\Http\Message\Upload\UploadedFile":private]=>
 string(9) "image/png"
 ["moved":"Swoft\Http\Message\Upload\UploadedFile":private]=>
      NULL
 ["path":"Swoft\Http\Message\Upload\UploadedFile":private]=>
      NULL
 }
 ...
 }
}


文件操作方法
moveTo() 將上傳的文件移動(dòng)到新位置。
getSize() 獲取文件大小,單位 byte。
getError() 獲取上傳文件相關(guān)的錯(cuò)誤信息,若無錯(cuò)將必須返回 UPLOAD_ERR_OK 常量,若又錯(cuò)誤將返回 UPLOAD_ERR_XXX 相關(guān)常量。
getClientFilename() 獲取文件上傳時(shí)客戶端本地的文件名,不要相信此方法返回的值??蛻舳丝赡軙?huì)發(fā)送惡意虛假文件名,意圖破壞或破解您的應(yīng)用程序。
getClientMediaType() 獲取客戶端中文件的 MediaType 類型,不要相信此方法返回的值。客戶端可能會(huì)發(fā)送惡意虛假文件名,意圖破壞或破解您的應(yīng)用程序。
其他常用輔助方法

if ($request->isAjax()) {
 // Do something
}
if ($request->isGet()) {
 // Do something
}
if ($request->isPost()) {
 // Do something
}


Http 響應(yīng)對象
根據(jù) PSR-7 對象的不可變性(immutable),所有的 with* 方法都是克隆對象然后返回,必須接收新對象來做進(jìn)一步處理,或使用鏈?zhǔn)秸{(diào)用
例如:

return $response->withContentType(ContentType::HTML)->withContent('<html lang="en"><h2>Swoft framework</h2></html>');


獲取響應(yīng)對象

$response=context()->getResponse()


設(shè)置響應(yīng)狀態(tài)碼

return $response->withStatus(404)


示例: 輸出字符串內(nèi)容響應(yīng)

return $response->withContent("Hello Swoft2.0");


示例: 輸出數(shù)組內(nèi)容響應(yīng)

$data = ['name'=>'Swoft2.0'];

return $response->withData($data);


示例: 設(shè)置響應(yīng)頭信息

return $response->withHeader("name","Swoft2.0");


示例: 重定向

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

// 404 page
return $response->redirect('/404');


示例: 文件下載

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


示例: 設(shè)置 Cookies

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

$response = $response->withCookie('name', [
 'value' => 'value3',
 'httpOnly' => true
]);
來源:https://8code.net/index/index/article/id/47

到此,關(guān)于“在swoft2中如何配置HTTP Server”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI