下載TP5框架,在項目根目錄下創建server目錄
http_service.php
<?php //創建服務 $http = new swoole_http_server("0.0.0.0", 8811); //設置參數 $http->set( [ 'enable_static_handler' => true, //開啟靜態資源目錄 'document_root' => "/home/work/hdtocs/swoole_mooc/thinkphp/public/static", //設置靜態資源目錄 'worker_num' => 4, //開啟進程數 ] ); //WorkerStart事件監聽進程啟動 //進程啟動時發生,這里創建的對象可以在進程生命周期內使用 //在進程啟動時加載ThinkPHP框架,啟動程序放在request回調中 $http->on('WorkerStart', function(swoole_server $server, $worker_id) { // 定義應用目錄 define('APP_PATH', __DIR__ . '/../application/'); // 加載框架里面的文件 require __DIR__ . '/../thinkphp/base.php'; }); //監聽用戶請求 //ThinkPHP Request對象是從PHP系統超全局數組 $_SERVER/$_GET/$_POST/$_SESSION 中獲取訪問信息,所以需要對這些數組進行初始化 //因為進程會常駐在內存中,所以在一次請求結束后相關的信息不會被銷毀,因此需要在賦值手動清空 $http->on('request', function($request, $response) use($http){ $_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; } } $_COOKIE = []; if(isset($request->cookie)) { foreach($request->cookie as $k => $v) { $_COOKIE[$k] = $v; } } //開啟ob ob_start(); // 執行應用並響應 try { think\Container::get('app', [APP_PATH]) ->run() ->send(); }catch (\Exception $e) { // todo } //從ob中讀取數據返回給客戶端 $res = ob_get_contents(); ob_end_clean(); $response->end($res); }); $http->start();
因為進程會常駐在內存中,所以在一次請求結束后相關的信息不會被銷毀,導致請求路徑發生變化時程序仍定位到前一次請求的方法,
原因:是因為TP框架在Request類中對pathinfo進行判斷,如果已存在則不再從$_SERVER中讀取
解決方案:在/thinkphp/library/think/Request.php pathinfo方法和path方法中修改判斷條件,使得每次請求都重新加載pathinfo
在請求時使用 域名:端口/模塊/控制器/方法?參數 的方法訪問時無法定位模塊
域名:端口/?s=模塊/控制器/方法?參數 使用這種方法可以解決
