HTTP Server

框架提供 HTTP Server,除非有特殊需求,否则能够满足日常大部分操作,与 PHP 内置web服务器同样操作。

设置 HTTPServer 仅需要对 class 选项进行调整即可。如下:

  1. <?php
  2. return [
  3. 'host' => 'http://0.0.0.0:9527',
  4. 'class' => \FastD\Servitization\Server\HTTPServer::class,
  5. 'options' => [
  6. 'pid_file' => __DIR__.'/../runtime/pid/'.app()->getName().'.pid',
  7. 'worker_num' => 10,
  8. 'task_worker_num' => 20,
  9. ],
  10. 'processes' => [
  11. ],
  12. 'listeners' => [
  13. ],
  14. ];

通过服务器命令启动服务:

  1. $ php bin/server start

核心实现逻辑代码:

  1. <?php
  2. namespace FastD\Servitization\Server;
  3. use FastD\Http\Response;
  4. use FastD\Http\SwooleServerRequest;
  5. use FastD\Servitization\OnWorkerStart;
  6. use FastD\Swoole\Server\HTTP;
  7. use Psr\Http\Message\ServerRequestInterface;
  8. use swoole_http_request;
  9. use swoole_http_response;
  10. class HTTPServer extends HTTP
  11. {
  12. use OnWorkerStart;
  13. public function onRequest(swoole_http_request $swooleRequet, swoole_http_response $swooleResponse)
  14. {
  15. $request = SwooleServerRequest::createServerRequestFromSwoole($swooleRequet);
  16. $response = $this->doRequest($request);
  17. foreach ($response->getHeaders() as $key => $header) {
  18. $swooleResponse->header($key, $response->getHeaderLine($key));
  19. }
  20. foreach ($response->getCookieParams() as $key => $cookieParam) {
  21. $swooleResponse->cookie($key, $cookieParam);
  22. }
  23. $swooleResponse->status($response->getStatusCode());
  24. $swooleResponse->end((string) $response->getBody());
  25. app()->shutdown($request, $response);
  26. }
  27. public function doRequest(ServerRequestInterface $serverRequest)
  28. {
  29. return app()->handleRequest($serverRequest);
  30. }
  31. }

当服务器收到请求的时候,会首先调用 onRequest 方法,在 onRequest 中,处理逻辑与fpm下一致.