初探 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 等头信息.
[本节完, 文字未校对, 程序待测试]