全局變量 (針對 easyswoole/http 在 1.6 ~ 2.0)
在 swoole
協程當中,我們都知道類似 $_GET
、$_SESSION
這樣的全局變量是不能安全使用的。原因是協程切換下會帶來數據污染問題。
驚喜
EasySwoole
在 spl
包中,實現了一個 SplContextArray
,并在主進程的位置,替換了這些全局變量,使得這些數據的訪問是安全的,并在請求結束后自動清理。從而我們可以在使用一些 FPM
環境下的組件包時沒有影響。
注冊
<?php
namespace EasySwoole\EasySwoole;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Http\GlobalParamHook;
use EasySwoole\Session\SessionFileHandler;
class EasySwooleEvent implements Event
{
public static function initialize()
{
date_default_timezone_set('Asia/Shanghai');
// 配置 session,設置 session 數據文件存儲目錄為 EASYSWOOLE_TEMP_DIR
$handler = new SessionFileHandler(EASYSWOOLE_TEMP_DIR);
GlobalParamHook::getInstance()->hookDefault();
// 如果不需要 session 請勿注冊
GlobalParamHook::getInstance()->hookSession($handler, 'easy_session', 'session_dir');
// onRequest v3.4.x+
\EasySwoole\Component\Di::getInstance()->set(\EasySwoole\EasySwoole\SysConst::HTTP_GLOBAL_ON_REQUEST, function (\EasySwoole\Http\Request $request, \EasySwoole\Http\Response $response) {
// 替換全局變量
GlobalParamHook::getInstance()->onRequest($request, $response);
});
// afterRequest v3.4.x+
\EasySwoole\Component\Di::getInstance()->set(\EasySwoole\EasySwoole\SysConst::HTTP_GLOBAL_AFTER_REQUEST, function (\EasySwoole\Http\Request $request, \EasySwoole\Http\Response $response) {
});
}
public static function mainServerCreate(EventRegister $register)
{
}
}
EasySwoole 3.4.x
版本之前:可在項目根目錄的 EasySwooleEvent.php
中看到 onRequest
及 afterRequest
方法。
事件注冊完畢后,即可使用
$_GET
、$_COOKIE
、$_POST
、$_FILES
、$_SERVER
、$_SESSION
。
使用
<?php
namespace App\HttpController;
use EasySwoole\Http\AbstractInterface\Controller;
class Index extends Controller
{
function index()
{
var_dump($_GET['a']);
if (isset($_SESSION['b'])) {
var_dump('last session is ' . $_SESSION['b']);
}
$_SESSION['b'] = time();
}
}
注意
該特性需要 1.6 版本以上的 http 組件庫
"easyswoole/http": "^1.6"