zanphpソースコード解読-リクエストと応答

3300 ワード

前言
これは私たちの最も関係のある一環かもしれません.Webアプリケーションは簡単に言えばリクエストと対応にほかならない.あなたが本当に協力しなければならない知識を得ました.でも.协程を知らないでプロセスを知っています~それではプロセスとして1つの要求の1つの进(xie)程を见にきます.スレッドを理解して~それではスレッドとして1つの要求の1つの線(xie)の程を見にきます
分析RequestHandler
vendor/zanphp/http-server/src/RequestHandler.php
class RequestHandler
{
    // ...
    
    //               
    $requestTask = new RequestTask($request, $swooleResponse, $this->context, $this->middleWareManager);
    $coroutine = $requestTask->run();
    $this->task = new Task($coroutine, $this->context);
    $this->task->run();
    clear_ob();
    // ..
}

RequestTaskの解析
vendor/zanphp/http-server/src/RequestTask.php
class RequestTask
{
    public function run()
    {
        yield $this->doRun();
    }
    
    public function doRun()
    {
        //          
        $response = (yield $this->middleWareManager->executeFilters());
        if (null !== $response) {
            $this->context->set('response', $response);
            /** @var ResponseTrait $response */
            yield $response->sendBy($this->swooleResponse);
            $this->context->getEvent()->fire($this->context->get('request_end_event_name'));
            return;
        }

        //               
        $dispatcher = Di::make(Dispatcher::class);
        $response = (yield $dispatcher->dispatch($this->request, $this->context));
        if (null === $response) {
            $code = BaseResponse::HTTP_INTERNAL_SERVER_ERROR;
            $response = new InternalErrorResponse("    ($code)", $code);
        }

        yield $this->middleWareManager->executePostFilters($response);

        $this->context->set('response', $response);
        yield $response->sendBy($this->swooleResponse);

        $this->context->getEvent()->fire($this->context->get('request_end_event_name'));
        clear_ob();
    }
}

分析Dispatcher
vendor/zanphp/http-server/src/Dispatcher.php
get('controller_name');
        $action = $context->get('action_name');
        $args   = $context->get('action_args');

        if ($args == null) {
            $args = [];
        }

        if ($controllerName === "/" && is_callable($action)) {
            yield $action(...array_values($args));
        } else {
            $controller = $this->getControllerClass($controllerName);
            if(!class_exists($controller)) {
                
                //        
                throw new PageNotFoundException("controller:{$controller} not found");
            }

            $controller = new $controller($request, $context);
            if(!is_callable([$controller, $action])) {
                
                //        
                throw new PageNotFoundException("action:{$action} is not callable in controller:" . get_class($controller));
            }
            yield $controller->$action(...array_values($args));
        }
    }

}