Application.php
3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace think\worker;
use think\App;
use think\Error;
use think\exception\HttpException;
use Workerman\Protocols\Http as WorkerHttp;
/**
* Worker应用对象
*/
class Application extends App
{
/**
* 处理Worker请求
* @access public
* @param \Workerman\Connection\TcpConnection $connection
* @param void
*/
public function worker($connection)
{
try {
ob_start();
// 重置应用的开始时间和内存占用
$this->beginTime = microtime(true);
$this->beginMem = memory_get_usage();
// 销毁当前请求对象实例
$this->delete('think\Request');
$pathinfo = ltrim(strpos($_SERVER['REQUEST_URI'], '?') ? strstr($_SERVER['REQUEST_URI'], '?', true) : $_SERVER['REQUEST_URI'], '/');
$this->request->setPathinfo($pathinfo);
if ($this->config->get('session.auto_start')) {
WorkerHttp::sessionStart();
}
// 更新请求对象实例
$this->route->setRequest($this->request);
$response = $this->run();
$response->send();
$content = ob_get_clean();
// Trace调试注入
if ($this->env->get('app_trace', $this->config->get('app_trace'))) {
$this->debug->inject($response, $content);
}
$this->httpResponseCode($response->getCode());
foreach ($response->getHeader() as $name => $val) {
// 发送头部信息
WorkerHttp::header($name . (!is_null($val) ? ':' . $val : ''));
}
$connection->send($content);
} catch (HttpException $e) {
$this->exception($connection, $e);
} catch (\Exception $e) {
$this->exception($connection, $e);
} catch (\Throwable $e) {
$this->exception($connection, $e);
}
}
protected function httpResponseCode($code = 200)
{
WorkerHttp::header('HTTP/1.1', true, $code);
}
protected function exception($connection, $e)
{
if ($e instanceof \Exception) {
$handler = Error::getExceptionHandler();
$handler->report($e);
$resp = $handler->render($e);
$content = $resp->getContent();
$code = $resp->getCode();
$this->httpResponseCode($code);
$connection->send($content);
} else {
$this->httpResponseCode(500);
$connection->send($e->getMessage());
}
}
}