请求 & 响应

    你可以用PSR-7中的 \Psr\Http\Message\ServerRequestInterface 来获得请求对象:

    也可以用 Cabal\Core\Http\Request 来获得请求对象:

    1. use Cabal\Core\Http\Request;
    2. use \Cabal\Core\Http\Server;
    3. $route->get('/hello/{name}', function (Server $server, Request $request, $vars = []) {
    4. return "hello " . $vars['name'];
    5. });

    ?> 无论哪种方式,你得到的都是一个 Cabal\Core\Http\Request 对象

    ?> 路由规则里匹配出来的的参数在 $vars 变量中。

    CabalPHP 会帮你将 GET 参数和 POST(请求体中的数据) 参数合并,优先使用 POST 中的参数。

      1. $request->all();
    • 只获取 usernamepassword,可以第一个参数传数组:

      1. $request->only(['username', 'password']);
    • 只获取 usernamepassword,可以传递多个参数:

      1. $request->only('username', 'password');
    • 判断是否是一个 ajax 请求(X-Requested-With=XMLHttpRequest):

      1. $request->isXhr();
    • 判断是否是制定的请求方法(GET HEAD OPTION DELETE HEAD等):

    • 获取参数 name 的值,不存在返回 null

      1. $request->input('name');
    • 获取除了 emailpassword 外的其他所有参数,可以传递多个参数:

      1. $request->except(['email','password']);
    • 获取上传的文件,你会得到一个实现了 Psr\Http\Message\UploadedFileInterface 接口的 Zend\Diactoros\UploadedFile 对象:

      1. $request->file('file');
    • 判断参数是否存在(isset),不包含上传的文件:

    • 判断参数是否不为空 (!empty || strlen > 0):

      1. $request->filled($name);
    1. 实现了 Psr\Http\Message\ResponseInterface 接口的对象
    1. use Cabal\Core\Http\Server;
    2. use Cabal\Core\Http\Response;
    3. use Cabal\Core\Http\Request;
    4. $route->get('/', function (\Cabal\Core\Http\Server $server, \Psr\Http\Message\ServerRequestInterface $request, $vars = []) {
    5. $response = new Response();
    6. // 必须重新赋值,PSR-7规定每次修改都是返回新对象哦
    7. $response = $response
    8. ->withStatus(500)
    9. ->withHeader('Version', 'alpha');
    10. $response->getBody()
    11. ->write('hello world');
    12. return $response;

    浏览器得到的完整HTTP响应:

    1. HTTP/1.1 500 Internal Server Error
    2. Version: alpha
    3. Server: swoole-http-server
    4. Connection: keep-alive
    5. Content-Type: text/html
    6. Date: Thu, 12 Apr 2018 16:27:02 GMT
    7. Content-Length: 11
    8. hello world
    1. 数组、stdClass或实现了\JsonSerializable的对象 - 输出 json_encode 后的字符串
    1. use Cabal\Core\Http\Server;
    2. use Cabal\Core\Http\Request;
    3. $route->get('/', function (\Cabal\Core\Http\Server $server, \Psr\Http\Message\ServerRequestInterface $request, $vars = []) {
    4. return ['code' => 0, 'msg' => 'hello world'];
    5. });
    1. render 方法的对象 - 输出 render 返回的字符串
    1. use Cabal\Core\Http\Server;
    2. use Cabal\Core\Http\Request;
    3. $route->get('/', function (\Cabal\Core\Http\Server $server, \Psr\Http\Message\ServerRequestInterface $request, $vars = []) {
    4. return ['code' => 0, 'msg' => 'hello world'];
    1. 字符串或数字 - 输出字符串或数字