继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Swoole完美支持Think5.1

码出一片_天
关注TA
已关注
手记 13
粉丝 6
获赞 27

1、首先创建一个http_server对象

在ThinkPHP目录下创建一个server目录,里面创建一个HTTP Server的php文件

2、需要在WorkerStart回调事件加载ThinkPHP核心文件

define('APP_PATH', __DIR__ . '/../application/');// 定义应用目录
require __DIR__ . '/../thinkphp/base.php'; //加载基础文件

3、转换TP可识别的请求类型

因为swoole接收get、post参数等和TP中接收不一样,所以需要转换为TP可识别,转换get参数示例如下:

$_GET = [];
if (isset($request->get)) {
    foreach ($request->get as $key => $value) {
        $_GET[$key] = $value;
    }
}

4、thinkphp会把模块、控制器、方法放到一个变量里去,所以通过pathinfo模式访问会存在只能访问第一次的pathinfo这个问题,worker进程里是不会注销变量的

解决办法:
thinkphp/library/think/Request.php
function path 中的if (is_null($this->path)) {}注释或删除
function pathinfo中的if (is_null($this->pathinfo)) {}注释或删除
注意:只删除条件,不删除条件中的内容

5、Swoole完美支持TP代码示例:

<?php
$http = new swoole_http_server("0.0.0.0", 8811);
$http->set(
    [
        'enable_static_handler' => true,
        'document_root' => "/home/thinkphp/public/static",
        'worker_num' => 5,
    ]
);
$http->on('WorkerStart', function(swoole_server $server,  $worker_id) {
    // 定义应用目录
    define('APP_PATH', __DIR__ . '/../application/');
    // 加载框架里面的文件
    require __DIR__ . '/../thinkphp/base.php';
    //require __DIR__ . '/../thinkphp/start.php';
});
$http->on('request', function($request, $response) use($http){

    //define('APP_PATH', __DIR__ . '/../application/');
    //require __DIR__ . '/../thinkphp/base.php';
    $_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_start();
    // 执行应用并响应
    try {
        think\Container::get('app', [APP_PATH])
            ->run()
            ->send();
    }catch (\Exception $e) {
        // todo
    }

    //echo "-action-".request()->action().PHP_EOL;
    $res = ob_get_contents();
    ob_end_clean();
    $response->end($res);
    //$http->close();
});

$http->start();

// topthink/think-swoole
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP