初探 Swoole -- 用 Swoole 啓動一個 hello worldphp
內存的妙用 -- PHP終於能夠 vs JAVA啦segmentfault
初級應用 -- 實現用戶註冊登陸 [撰寫中]數組
展望 -- Swoole 的侷限性分析及我我的的期待 [撰寫中]瀏覽器
還記得咱們第一個 PHP 程序嗎?swoole
<?php echo "hello world";
把他保存到 hello.php
, 訪問 http://localhost/hello.php
就能夠輸出 hello world. 不少人就是這兩行代碼引入了 PHP 的大門.app
咱們用 Swoole 來作一個框架
<?php $http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE); $http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) { $res->write("hello world"); $res->end(); });
OK, 看出了吧, 不依賴框架/ ob_flush 等機制, Swoole 不能再使用 echo 做爲輸出方法了, 得使用$res->write(String $content)
和 $res->end(String $endContent)
.post
那麼咱們怎麼訪問它呢?
命令行啓動測試
php app.php # 你在代碼裏面 echo/var_dump/print(_r) 的內容將在這裏輸出
而後在瀏覽器打開 http://localhost/
就能夠獲得 hello world
的輸出.
但是發現了嗎? http://localhost/
和 http://localhost/xxx
都輸出一樣的內容.
若是咱們只想讓 php 在 http://localhost/
下輸出, 怎麼寫呢?命令行
<?php $http = new swoole_http_server('0.0.0.0', 80, SWOOLE_BASE); $http->on('request', function(swoole_http_request $req, swoole_http_response $res) use($http) { if($req->server['request_uri'] == '/'){ $res->write("hello world"); $res->end(); return; } $res->end('404'); return; });
\Swoole_http_request $req
包含了不少咱們未來能用到的請求數據. 包括 $req->server
, $req->get
, $req->post
, 數組結構, ->server的KEY 爲小寫
提早說個坑, swoole http request 對象的 server 數據不完整, 獲取不到諸如 connection/origin 等頭信息.
[本節完, 文字未校對, 程序待測試]