/**
* @woole整合yii
* @authors Tyloafer (tyloafer@gmail.com)
* @date 2018-05-09 08:22:21
*/
class SwooleIndex
{
private $swoole;
private $config;
public function __construct()
{
$option = [
'enable_static_handler' => true,
'document_root' => "/home/lixy/basic/",
'worker_num' => 5,
'log_level' => 3,
];
$this->swoole = new \Swoole\Http\Server('0.0.0.0', 9502);
$this->swoole->set($option);
$this->swoole->on('workerstart', [$this, 'workerStart']);
$this->swoole->on('request', [$this, 'request']);
}
public function __call($name, $args)
{
return call_user_func_array([$this, $name], $args);
}
public function workerStart($server, $id)
{
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';
$this->config = require __DIR__ . '/../config/web.php';
}
public function request($request, $response)
{
$this->initParams($request);
ob_start();
(new yii\web\Application($this->config))->run();
$content = ob_get_contents();
ob_clean();
$response->end($content);
}
private function initParams($request)
{
$mapping = [
'header' => ['suffix' => 'http', 'name' => '_SERVER', 'toupper' => true, 'replace_slash' => true],
'server' => ['suffix' => '', 'name' => '_SERVER', 'toupper' => true, 'replace_slash' => false],
'request' => ['suffix' => '', 'name' => '_REQUEST', 'toupper' => true, 'replace_slash' => false],
'cookie' => ['suffix' => '', 'name' => '_COOKIE', 'toupper' => false, 'replace_slash' => false],
'get' => ['suffix' => '', 'name' => '_GET', 'toupper' => false, 'replace_slash' => false],
'post' => ['suffix' => '', 'name' => '_POST', 'toupper' => false, 'replace_slash' => false],
'files' => ['suffix' => '', 'name' => '_FILES', 'toupper' => false, 'replace_slash' => false],
];
// 先赋值为空,防止以前的请求对后面的请求产生影响
foreach ($mapping as $value) {
$_GET = [];
$_POST = [];
$_FILES = [];
$_COOKIE = [];
$_REQUEST = [];
// $_SERVER = [];
}
// 针对mapping里面的循环赋值
foreach ($mapping as $key => $value) {
if (!empty($request->$key)) {
foreach ($request->$key as $name => $val) {
if (!empty($value['suffix'])) {
$name = $value['suffix'] . '_' . $name;
}
if ($value['toupper'] === true) {
$name = strtoupper($name);
}
if ($value['replace_slash'] === true) {
$name = str_replace('-', '_', $name);
}
${strtoupper($value['name'])}[$name] = $val;
}
} else {
${strtoupper($value['name'])} = [];
}
$data[strtoupper($value['name'])] = ${strtoupper($value['name'])};
}
$_GET = $data['_GET'];
$_POST = $data['_POST'];
$_FILES = $data['_FILES'];
$_COOKIE = $data['_COOKIE'];
$_REQUEST = $data['_REQUEST'];
$_SERVER = array_merge($data['_SERVER'], $_SERVER);
// return true;
}
}
$swoole_index = new SwooleIndex();
$swoole_index->start();