前言
也许这是我们最关系的一个环节了。一个web应用简单来说无非就是请求和相应了。
获取你真的该补补 协程 的相关知识了。不过。。
不懂协程懂进程~ 那就 当成进程来看 一个请求一个进 (xie) 程.
懂线程~ 那就 当成 线程来看 一个请求一个线 (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
<?php
class Dispatcher
{
public function dispatch(Request $request, Context $context)
{
// 看到这些 你应该似曾相识
$controllerName = $context->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));
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。