<?php
/**
* Created by PhpStorm.
* User: weijianhua
* Date: 18/7/5
* Time: 下午9:53
*/
class Http
{
const HOST = '0.0.0.0';
const PORT = 8811;
public $http = null;
public function __construct()
{
$this->http = new swoole_http_server(self::HOST, self::PORT);
$this->http->set(
[
'enable_static_handler' => true,
'document_root' => '/Users/weijianhua/Sites/test/swoole/mooc/thinkphp5/public/static/live',
'worker_num' => 4,
'task_worker_num' => 4,
]
);
$this->http->on('WorkerStart', [$this, 'onWorkerStart']);
$this->http->on('Request', [$this, 'onRequest']);
$this->http->on('Task', [$this, 'onTask']);
$this->http->on('Finish', [$this, 'onFinish']);
$this->http->on('Close', [$this, 'onClose']);
$this->http->start();
}
public function onWorkerStart($server, $worker_id)
{
//定义应用进程
define('APP_PATH', __DIR__ . '/../application/');
// require __DIR__ . '/../thinkphp/start.php';
require __DIR__ . '/../thinkphp/base.php';
}
public function onRequest($request, $response)
{
echo 'Request '.PHP_EOL;
if (isset($request->server)) {
foreach ($request->server as $k => $v) {
$_SERVER[$k] = $v;
}
}
// 有 $http->close() 就不用这个了
/*if (!empty($_GET)) {
unset($_GET); // 超全局变量进程没挂,一直会存在
}*/
if (isset($request->get)) {
foreach ($request->get as $k => $v) {
$_GET[$k] = $v;
}
}
if (isset($request->post)) {
foreach ($request->post as $k => $v) {
$_POST[$k] = $v;
}
}
$_POST['http_server'] = $this->http;
ob_start();
try {
think\App::run()->send();
} catch (\Exception $e) {
var_dump($e->getMessage());
die('123');
}
//echo ' -- action -- '.request()->action() . PHP_EOL;
$content = ob_get_contents();
ob_end_clean();
$response->end($content);
}
public function onFinish($server, $taskID, $data)
{
}
public function onTask($server, $taskID, $workerID, $data)
{
echo 'Task '.PHP_EOL;
var_dump($data);
}
public function onClose($server, $fd, $reactorID)
{
echo 'Close'.PHP_EOL;
}
}
new Http();
在 onWorkerStart 中引入框架内容,可以常驻内存,这样就可以在任何地方使用框架的代码。
在 onRequest() 中引入的话, 相当于 PHP-FPM 模式,请求结束就结束了。