Swoole实战之手撸HttpServer框架 2 使用第三方组件nikic/FastRoute自定义路由、简单封装Request对象

1 启动项目

 D:seckillproindex.php

<?php

use SwooleHttpRequest;
use SwooleHttpResponse;
$http  = new SwooleHttpServer("0.0.0.0",80);
$http->on('request',function (Request $request,Response $response){
    $html = $request->server['request_uri'];
   
    if($request->server['request_uri']=='/test'){
        $response->end("<h1>test</h1>");
        return;
    }
    $response->end("<h1>hello</h1>");
});
$http->start();

 

2 使用组件nikic/FastRoute

 composer require nikic/fast-route

 D:seckillproindex.php

<?php
//https://github.com/nikic/FastRoute
require_once __DIR__.'/vendor/autoload.php';
use SwooleHttpRequest;
use SwooleHttpResponse;

//注册路由
$dispatcher = FastRoutesimpleDispatcher(function (FastRouteRouteCollector $r){
   $r->addRoute('GET','/test',function (){
       return 'my test';
   });
});
$http  = new SwooleHttpServer("0.0.0.0",80);

$http->on('request',function (Request $request,Response $response) use($dispatcher) {
   //匹配当前的url
    $routeInfo = $dispatcher->dispatch($request->server['request_method'],$request->server['request_uri']);
    //$routeInfo返回一个数组,[表示是否注册过的路由,handle,参数]
    switch ($routeInfo[0]) {
        case FastRouteDispatcher::NOT_FOUND:
            // ... 404 Not Found 结束响应 
            $response->status(404);
            $response->end();
            break;
        case FastRouteDispatcher::METHOD_NOT_ALLOWED:
            //$allowedMethods = $routeInfo[1];
            // ... 405 Method Not Allowed
            $response->status(405);
            $response->end();
            break;
        case FastRouteDispatcher::FOUND:
            $handler = $routeInfo[1];
            //$vars = $routeInfo[2];
            // ... call $handler with $vars
            $response->end($handler());
            break;
    }
    
});
$http->start();

 3 封装Request

 D:seckillproappcoreRequest.php

<?php
namespace Appcore;
class Request
{
   protected $server = [];
   protected $uri ;
   protected $queryParams;
   protected $postParams;
   protected $method;
   protected $header=[];
   protected $body;
   protected $swooleRequest;

 

 

 选中除swooleRequest外全部

 自动生成和get和set方法

 完整代码

D:seckillproappcoreRequest.php

<?php
namespace Appcore;
class Request
{
   protected $server = [];
   protected $uri ;
   protected $queryParams;
   protected $postParams;
   protected $method;
   protected $header = [];
   protected $body;
   protected $swooleRequest;
    
    /**
     * Request constructor.
     *
     * @param array $server
     * @param       $uri
     * @param       $queryParams
     * @param       $postParams
     * @param       $method
     * @param array $header
     * @param       $body
     */
    public function __construct(
      array $server,
      $uri,
      $queryParams,
      $postParams,
      $method,
      array $header,
      $body
    ) {
        $this->server = $server;
        $this->uri = $uri;
        $this->queryParams = $queryParams;
        $this->postParams = $postParams;
        $this->method = $method;
        $this->header = $header;
        $this->body = $body;
    }
    
    /**
     * @return array
     */
    public function getServer(): array
    {
        return $this->server;
    }
    
    /**
     * @param array $server
     */
    public function setServer(array $server): void
    {
        $this->server = $server;
    }
    
    /**
     * @return mixed
     */
    public function getUri()
    {
        return $this->uri;
    }
    
    /**
     * @param mixed $uri
     */
    public function setUri($uri): void
    {
        $this->uri = $uri;
    }
    
    /**
     * @return mixed
     */
    public function getQueryParams()
    {
        return $this->queryParams;
    }
    
    /**
     * @param mixed $queryParams
     */
    public function setQueryParams($queryParams): void
    {
        $this->queryParams = $queryParams;
    }
    
    /**
     * @return mixed
     */
    public function getPostParams()
    {
        return $this->postParams;
    }
    
    /**
     * @param mixed $postParams
     */
    public function setPostParams($postParams): void
    {
        $this->postParams = $postParams;
    }
    
    /**
     * @return mixed
     */
    public function getMethod()
    {
        return $this->method;
    }
    
    /**
     * @param mixed $method
     */
    public function setMethod($method): void
    {
        $this->method = $method;
    }
    
    /**
     * @return array
     */
    public function getHeader(): array
    {
        return $this->header;
    }
    
    /**
     * @param array $header
     */
    public function setHeader(array $header): void
    {
        $this->header = $header;
    }
    
    /**
     * @return mixed
     */
    public function getBody()
    {
        return $this->body;
    }
    
    /**
     * @param mixed $body
     */
    public function setBody($body): void
    {
        $this->body = $body;
    }
    
    /**
     * @return mixed
     */
    public function getSwooleRequest()
    {
        return $this->swooleRequest;
    }
    
    /**
     * @param mixed $swooleRequest
     */
    public function setSwooleRequest($swooleRequest): void
    {
        $this->swooleRequest = $swooleRequest;
    }

    
    public static function init(SwooleHttpRequest $swooleRequest)
    {
       $server  = $swooleRequest->server;
       //$a = $a ?? 1; 判断一个变量是a否存在,存在则赋值变量a,不存在赋值变量b
       $method  = $swooleRequest->server['request_method'] ?? 'GET';
       $uri     = $server['request_uri'];
       $body    = $swooleRequest->rawContent();
       
       $request = new self($server,$uri,$swooleRequest->get,$swooleRequest->post,$method,$swooleRequest->header,$body);
       
       $request->swooleRequest = $swooleRequest;
       return $request;
    }
    
    
}

D:seckillproindex.php

<?php
//https://github.com/nikic/FastRoute
require_once __DIR__.'/vendor/autoload.php';
use SwooleHttpRequest;
use SwooleHttpResponse;

//注册路由
$dispatcher = FastRoutesimpleDispatcher(function (FastRouteRouteCollector $r){
   $r->addRoute('GET','/test',function (){
       return 'my test';
   });
});
$http  = new SwooleHttpServer("0.0.0.0",80);

$http->on('request',function (Request $request,Response $response) use($dispatcher) {
    
    //匹配当前的url
    //$routeInfo = $dispatcher->dispatch($request->server['request_method'],$request->server['request_uri']);
    $myRequery = AppcoreRequest::init($request);
    $routeInfo = $dispatcher->dispatch($myRequery->getMethod(),$myRequery->getUri());
    //$routeInfo返回一个数组,[表示是否注册过的路由,handle,参数]
    switch ($routeInfo[0]) {
        case FastRouteDispatcher::NOT_FOUND:
            // ... 404 Not Found 结束响应 
            $response->status(404);
            $response->end();
            break;
        case FastRouteDispatcher::METHOD_NOT_ALLOWED:
            //$allowedMethods = $routeInfo[1];
            // ... 405 Method Not Allowed
            $response->status(405);
            $response->end();
            break;
        case FastRouteDispatcher::FOUND:
            $handler = $routeInfo[1];
            //$vars = $routeInfo[2];
            // ... call $handler with $vars
            $response->end($handler());
            break;
    }
    
});
$http->start();

 代码下载

https://github.com/guainttt/seckill/archive/refs/tags/v1.0.zip

原文地址:https://www.cnblogs.com/polax/p/15450153.html