1.在项目目录中创建server文件夹用来存放swoole服务端文件
2.sever中代码
<?php use think\Container; $http = new Swoole\Http\Server('0.0.0.0', 9501); $http->set([ 'worker_num' => 4, 'log_file'=>'./success.log', 'document_root'=>"/Users/wangyalun/Desktop/phptm/tpsw/public/static/live", 'enable_static_handler' => true, ]); //注入要启动时引入入口文件 $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) {
//将icon请求直接返回 if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') { $response->end(); return; }
//为了避免请求被缓存 赋值为空数组 $_SERVER = []; if (isset($request->server)) { foreach ($request->server as $k => $v) { $_SERVER[strtoupper($k)] = $v; } } if (isset($request->header)) { foreach ($request->header as $k => $v) { $_SERVER[strtoupper($k)] = $v; } } $_GET = []; if (isset($request->get)) { foreach ($request->get as $k => $v) { $_GET[$k] = $v; } } $_POST = []; if (isset($request->post)) { foreach ($request->post as $k => $v) { $_POST[$k] = $v; } } //开启ob缓存 ob_start(); try { think\Container::get('app',[defined('APP_PATH') ? APP_PATH : ''])->run()->send(); }catch (\Exception $e){ echo $e->getMessage(); file_put_contents("error.log",json_encode([$e->getMessage()])); }
//读取ob缓存区内容 $res=ob_get_contents(); ob_clean(); $response->end($res); }); $http->start();
3.解决路由不更新问题
查看thinkphp下App.php run()方法
$this->request->path();这段代码指向的是thinkphp/library/think/Request.php文件中的path()方法:
注释掉判断为空的方法
以及pathinfo方法中的is_null($this->pathinfo)
注意⚠️这样修改后仍是index, 因为使用swoole的http_server进行访问的时候默认是cli模式
将 $pathinfo = isset( ['argv'][1]) ? $_SERVER['argv'][1] : ''; 替换成$pathinfo= isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : $_SERVER['REQUEST_URI'];