aloefflerj / yet-another-controller
基本上这是一个尽可能使用PSR的http请求和响应控制器(或者只是一个个人学习的借口)
Requires
- guzzlehttp/guzzle: ^7.5
- psr/http-message: ^1.0
- vishnubob/wait-for-it: dev-master
Requires (Dev)
- phpunit/phpunit: 10.0.*
- symfony/var-dumper: ^6.2
README
以下是它的工作方式(目前)
安装
composer require aloefflerj/yet-another-controller
快速使用
-
简单设置
index.php
<?php declare(strict_types=1); use Aloefflerj\YetAnotherController\Controller\Controller; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; require_once '/vendor/autoload.php'; $controller = new Controller('https://:8000');
-
添加简单的 GET 路由
index.php
$controller->get('/', function (RequestInterface $request, ResponseInterface $response) { $response->getBody()->write('Welcome home'); return $response->getBody(); });
-
分发路由
index.php
$controller->dispatch();
-
启动您的Web服务器
启动Web服务器的简单方法是用PHP内置Web服务器:
运行
php -S localhost:8000 -t path/to/your/index
-
访问您的域名主页
https://:8000/
输出: '欢迎回家'
请求和响应
closure
的 $request
和 $response
参数是 PSR-7 实现。
closure
的返回值必须是一个 StreamInterface
实现,以便输出可以工作。
$controller->get('/', function (RequestInterface $request, ResponseInterface $response) { $response->getBody()->write('Welcome home'); return $response->getBody(); });
由于 $response->getBody()
的返回值是一个 StreamInterface
实现,因此上面的代码将打印
输出: '欢迎回家'
或者你可以简单地这样做 echo $response->getBody();
Uri参数使用
您可以使用 /route/{param}
语法传递uri参数。
为了访问 param
,您需要在 get
方法中添加第三个参数:\stdClass $args
。
为了在 closure
的 output 中访问它,您必须使用 $args->param
。请看下面的示例
$controller->get('/mascots/{mascot}', function (RequestInterface $request, ResponseInterface $response, \stdClass $args) { $response->getBody()->write("PHP {$args->mascot} mascot is awesome"); return $response->getBody(); });
url: localhost:8000/mascots/elephant
输出: 'PHP大象吉祥物很棒'
获取请求体
要从请求中获取体,您可以通过 $request
实现访问它,使用 $request->getBody()
(一个 StreamInterface
实现)。
下面的示例将打印请求体。
$controller->put('/mascot', function (RequestInterface $request, ResponseInterface $response) { $requestBody = $request->getBody(); return $requestBody; });
如果我用以下体请求 POST
{ "mascots": [ { "lang": "php", "mascot": "elephant" }, { "lang": "go", "mascot": "gopher" } ] }
返回应该是一样的
{ "mascots": [ { "lang": "php", "mascot": "elephant" }, { "lang": "go", "mascot": "gopher" } ] }