Swoole完美支持ThinkPHP5
一、首先要開啓http的server
- 能夠在thinkphp的目錄下建立一個server目錄,裏面建立一個HTTPServer的php
二、須要在WorkerStart回調事件作兩件事
- 定義應用目錄:
define('APP_PATH', __DIR__ . '/../application/');
- 加載基礎文件:
require __DIR__ . '/../thinkphp/base.php';
三、由於swoole接收get、post參數等和thinkphp中接收不同,因此須要轉換爲thinkphp可識別,轉換get參數示例以下:
注意點: swoole對於超全局數組:
$_SERVER
、
$_GET
、
$_POST
、
define定義的常量
等不會釋放,因此須要先清空一次
// 先清空
$_GET = [];
if (isset($request->get)) {
foreach ($request->get as $key => $value) {
$_GET[$key] = $value;
}
}
四、thinkphp會把模塊、控制器、方法放到一個變量裏去,因此經過pathinfo模式訪問會存在只能訪問第一次的pathinfo這個問題,worker進程裏是不會註銷變量的
解決辦法:
thinkphp/library/think/Request.php
function path
中的
if (is_null($this->path)) {}
註釋或刪除
function pathinfo
中的
if (is_null($this->pathinfo)) {}
註釋或刪除
注意:只刪除條件,不刪除條件中的內容
五、swoole支持thinkphp的http_server示例:
// 面向過程寫法
$http = new swoole_http_server('0.0.0.0', 9501);
$http->set([
// 開啓靜態資源請求
'enable_static_handler' => true,
'document_root' => '/opt/app/live/public/static',
'worker_num' => 5,
]);
/**
* WorkerStart事件在Worker進程/Task進程啓動時發生。這裏建立的對象能夠在進程生命週期內使用
* 目的:加載thinkphp框架中的內容
*/
$http->on('WorkerStart', function (swoole_server $server, $worker_id) {
// 定義應用目錄
define('APP_PATH', __DIR__ . '/../application/');
// 加載基礎文件
require __DIR__ . '/../thinkphp/base.php';
});
$http->on('request', function ($request, $response) {
// 把swoole接收的信息轉換爲thinkphp可識別的
$_SERVER = [];
if (isset($request->server)) {
foreach ($request->server as $key => $value) {
$_SERVER[strtoupper($key)] = $value;
}
}
if (isset($request->header)) {
foreach ($request->header as $key => $value) {
$_SERVER[strtoupper($key)] = $value;
}
}
// swoole對於超全局數組:$_SERVER、$_GET、$_POST、define不會釋放
$_GET = [];
if (isset($request->get)) {
foreach ($request->get as $key => $value) {
$_GET[$key] = $value;
}
}
$_POST = [];
if (isset($request->post)) {
foreach ($request->post as $key => $value) {
$_POST[$key] = $value;
}
}
// ob函數輸出打印
ob_start();
try {
think\Container::get('app', [APP_PATH]) ->run() ->send();
$res = ob_get_contents();
ob_end_clean();
} catch (\Exception $e) {
// todo
}
$response->end($res);
});
$http->start();