百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Mix Vega 发布,支持 Swoole、WorkerMan 的 CLI HTTP 网络框架

ccwgpt 2024-10-10 04:55 21 浏览 0 评论

Mix Vega

Vega 是一个用 PHP 编写的 CLI HTTP 网络框架,支持 Swoole、WorkerMan

Overview

Vega 是 MixPHP V3+ 内置的最核心的组件 (可独立使用),参考
golang gin mux 开发,它包含 Web 应用处理的大量功能 (数据库处理除外)
,包括:路由、渲染、参数获取、中间件、文件上传处理等;具有 CLI 模式下强大的兼容性,同时支持 Swoole、WorkerMan, 并且支持 Swoole 的多种进程模型。

源码地址

Star 一下不迷路,下次用的时候还能找到

  • https://github.com/mix-php/vega
  • https://gitee.com/mix-php/vega

Installation

需要先安装 Swoole 或者 WorkerMan

composer require mix/vega

Quick start

Swoole 多进程 (异步) 中使用

<?php
require __DIR__ . '/vendor/autoload.php';

$vega = new Mix\Vega\Engine();
$vega->handleF('/hello', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET');

$http = new Swoole\Http\Server('0.0.0.0', 9501);
$http->on('Request', $vega->handler());
$http->start();

Swoole 单进程 (协程) 中使用

<?php
require __DIR__ . '/vendor/autoload.php';

Swoole\Coroutine\run(function () {
    $vega = new Mix\Vega\Engine();
    $vega->handleF('/hello', function (Mix\Vega\Context $ctx) {
        $ctx->string(200, 'hello, world!');
    })->methods('GET');
    
    $server = new Swoole\Coroutine\Http\Server('127.0.0.1', 9502, false);
    $server->handle('/', $vega->handler());
    $server->start();
});

WorkerMan 中使用

<?php
require __DIR__ . '/vendor/autoload.php';

$vega = new Mix\Vega\Engine();
$vega->handleF('/hello', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET');

$http_worker = new Workerman\Worker("http://0.0.0.0:2345");
$http_worker->onMessage = $vega->handler();
$http_worker->count = 4;
Workerman\Worker::runAll();

访问测试

% curl http://0.0.0.0:9501/hello
hello, world!

路由配置

配置 Closure 闭包路由

$vega = new Mix\Vega\Engine();
$vega->handleF('/hello', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET');

配置 callable 路由

class Hello {
    public function index(Mix\Vega\Context $ctx) {
        $ctx->string(200, 'hello, world!');
    }
}
$vega = new Mix\Vega\Engine();
$vega->handleC('/hello', [new Hello(), 'index'])->methods('GET');

配置路由变量

$vega = new Mix\Vega\Engine();
$vega->handleF('/users/{id}', function (Mix\Vega\Context $ctx) {
    $id = $ctx->param('id');
    $ctx->string(200, 'hello, world!');
})->methods('GET');

配置多个 method

$vega = new Mix\Vega\Engine();
$vega->handleF('hello', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET', 'POST');

路由前缀 (分组)

$vega = new Mix\Vega\Engine();
$subrouter = $vega->pathPrefix('/foo');
$subrouter->handleF('/bar1', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET');
$subrouter->handleF('/bar2', function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello1, world!');
})->methods('GET');

参数获取

请求参数

方法名称

描述

$ctx->param(string $key): string

获取路由参数

$ctx->query(string $key): string

获取url参数,包含路由参数

$ctx->defaultQuery(string $key, string $default): string

获取url参数,可配置默认值

$ctx->getQuery(string $key): string or null

获取url参数, 可判断是否存在

$ctx->postForm(string $key): string

获取post参数

$ctx->defaultPostForm(string $key, string $default): string

获取post参数,可配置默认值

$ctx->getPostForm(string $key): string or null

获取post参数,可判断是否存在

Headers, Cookies, Uri ...

方法名称

描述

$ctx->contentType(): string

请求类型

$ctx->header(string $key): string

请求头

$ctx->cookie(string $name): string

cookies

$ctx->uri(): UriInterface

完整uri

$ctx->rawData(): string

原始包数据

客户端IP

方法名称

描述

$ctx->clientIP(): string

从反向代理获取用户真实IP

$ctx->remoteIP(): string

获取远程IP

上传文件处理

方法名称

描述

$ctx->formFile(string $name): UploadedFileInterface

获取上传的第一个文件

$ctx->multipartForm(): UploadedFileInterface[]

获取上传的全部文件

文件保存

$file = $ctx->formFile('img');
$targetPath = '/data/uploads/' . $file->getClientFilename();
$file->moveTo($targetPath);

请求上下文

请求当中需要保存一些信息,比如:会话、JWT载荷等。

方法名称

描述

$ctx->set(string $key, $value): void

设置值

$ctx->get(string $key): mixed or null

获取值

$ctx->mustGet(string $key): mixed or throws

获取值或抛出异常

中断执行

abort 执行后,会停止执行后面的全部代码,包括中间件。

$vega = new Mix\Vega\Engine();
$vega->handleF('/users/{id}', function (Mix\Vega\Context $ctx) {
    if (true) {
        $ctx->string(401, 'Unauthorized');
        $ctx->abort();
    }
    $ctx->string(200, 'hello, world!');
})->methods('GET');

响应处理

方法名称

描述

$ctx->status(int $code): void

设置状态码

$ctx->setHeader(string $key, string $value): void

设置header

$ctx->setCookie(string $name, string $value, int $expire = 0, ...): void

设置cookie

$ctx->redirect(string $location, int $code = 302): void

重定向

JSON 请求与输出

获取 JSON 请求数据

$vega = new Mix\Vega\Engine();
$vega->handleF('/users', function (Mix\Vega\Context $ctx) {
    $obj = $ctx->getJSON();
    if (!$obj) {
        throw new \Exception('Parameter error');
    }
    var_dump($obj);
    $ctx->JSON(200, [
        'code' => 0,
        'message' => 'ok'
    ]);
})->methods('POST');

mustGetJSON 自带有效性检查,以下代码等同于上面

$vega = new Mix\Vega\Engine();
$vega->handleF('/users', function (Mix\Vega\Context $ctx) {
    $obj = $ctx->mustGetJSON();
    var_dump($obj);
    $ctx->JSON(200, [
        'code' => 0,
        'message' => 'ok'
    ]);
})->methods('POST');

JSONP 处理

$vega = new Mix\Vega\Engine();
$vega->handleF('/jsonp', function (Mix\Vega\Context $ctx) {
    $ctx->JSONP(200, [
        'code' => 0,
        'message' => 'ok'
    ]);
})->methods('GET');

设置中间件

给某个路由配置中间件,可配置多个

$vega = new Mix\Vega\Engine();
$func = function (Mix\Vega\Context $ctx) {
    // do something
    $ctx->next();
};
$vega->handleF('/hello', $func, function (Mix\Vega\Context $ctx) {
    $ctx->string(200, 'hello, world!');
})->methods('GET');

配置全局中间件,即便没有匹配到路由也会执行

$vega = new Mix\Vega\Engine();
$vega->use(function (Mix\Vega\Context $ctx) {
    $ctx->next();
});

前置中间件

$vega->use(function (Mix\Vega\Context $ctx) {
    // do something
    $ctx->next();
});

后置中间件

$vega->use(function (Mix\Vega\Context $ctx) {
    $ctx->next();
    // do something
});

404 自定义

$vega = new Mix\Vega\Engine();
$vega->use(function (Mix\Vega\Context $ctx) {
    try{
        $ctx->next();
    } catch (Mix\Vega\Exception\NotFoundException $ex) {
        $ctx->string(404, 'New 404 response');
        $ctx->abort();
    }
});

500 全局异常捕获

$vega = new Mix\Vega\Engine();
$vega->use(function (Mix\Vega\Context $ctx) {
    try{
        $ctx->next();
    } catch (\Throwable $ex) {
        $ctx->string(500, 'New 500 response');
        $ctx->abort();
    }
});

HTML 视图渲染

创建视图文件 foo.php

<p>id: <?= $id ?>, name: <?= $name ?></p>
<p>friends:</p>
<ul>
    <?php foreach($friends as $name): ?>
        <li><?= $name ?></li>
    <?php endforeach; ?>
</ul>

配置视图路径,并响应html

$vega = new Mix\Vega\Engine();
$vega->withHTMLRoot('/data/project/views');
$vega->handleF('/html', function (Mix\Vega\Context $ctx) {
    $ctx->HTML(200, 'foo', [
        'id' => 1000,
        'name' => '小明',
        'friends' => [
            '小花',
            '小红'
        ]
    ]);
})->methods('GET');

License

Apache License Version 2.0, http://www.apache.org/licenses/

相关推荐

团队管理“布阵术”:3招让你的团队战斗力爆表!

为何古代军队能够以一当十?为何现代企业有的团队高效似“特种部队”,有的却松散若“游击队”?**答案正隐匿于“布阵术”之中!**今时今日,让我们从古代兵法里萃取3个核心要义,助您塑造一支战斗力爆棚的...

知情人士回应字节大模型团队架构调整

【知情人士回应字节大模型团队架构调整】财联社2月21日电,针对原谷歌DeepMind副总裁吴永辉加入字节跳动后引发的团队调整问题,知情人士回应称:吴永辉博士主要负责AI基础研究探索工作,偏基础研究;A...

豆包大模型团队开源RLHF框架,训练吞吐量最高提升20倍

强化学习(RL)对大模型复杂推理能力提升有关键作用,但其复杂的计算流程对训练和部署也带来了巨大挑战。近日,字节跳动豆包大模型团队与香港大学联合提出HybridFlow。这是一个灵活高效的RL/RL...

创业团队如何设计股权架构及分配(创业团队如何设计股权架构及分配方案)

创业团队的股权架构设计,决定了公司在随后发展中呈现出的股权布局。如果最初的股权架构就存在先天不足,公司就很难顺利、稳定地成长起来。因此,创业之初,对股权设计应慎之又慎,避免留下巨大隐患和风险。两个人如...

消息称吴永辉入职后引发字节大模型团队架构大调整

2月21日,有消息称前谷歌大佬吴永辉加入字节跳动,并担任大模型团队Seed基础研究负责人后,引发了字节跳动大模型团队架构大调整。多名原本向朱文佳汇报的算法和技术负责人开始转向吴永辉汇报。简单来说,就是...

31页组织效能提升模型,经营管理团队搭建框架与权责定位

分享职场干货,提升能力!为职场精英打造个人知识体系,升职加薪!31页组织效能提升模型如何拿到分享的源文件:请您关注本头条号,然后私信本头条号“文米”2个字,按照操作流程,专人负责发送源文件给您。...

异形柱结构(异形柱结构技术规程)

下列关于混凝土异形柱结构设计的说法,其中何项正确?(A)混凝土异形柱框架结构可用于所有非抗震和抗震设防地区的一般居住建筑。(B)抗震设防烈度为6度时,对标准设防类(丙类)采用异形柱结构的建筑可不进行地...

职场干货:金字塔原理(金字塔原理实战篇)

金字塔原理的适用范围:金字塔原理适用于所有需要构建清晰逻辑框架的文章。第一篇:表达的逻辑。如何利用金字塔原理构建基本的金字塔结构受众(包括读者、听众、观众或学员)最容易理解的顺序:先了解主要的、抽象的...

底部剪力法(底部剪力法的基本原理)

某四层钢筋混凝土框架结构,计算简图如图1所示。抗震设防类别为丙类,抗震设防烈度为8度(0.2g),Ⅱ类场地,设计地震分组为第一组,第一自振周期T1=0.55s。一至四层的楼层侧向刚度依次为:K1=1...

结构等效重力荷载代表值(等效重力荷载系数)

某五层钢筋混凝土框架结构办公楼,房屋高度25.45m。抗震设防烈度8度,设防类别丙类,设计基本地震加速度0.2g,设计地震分组第二组,场地类别为Ⅱ类,混凝土强度等级C30。该结构平面和竖向均规则。假定...

体系结构已成昭告后世善莫大焉(体系构架是什么意思)

实践先行也理论已初步完成框架结构留余后人后世子孙俗话说前人栽树后人乘凉在夏商周大明大清民国共和前人栽树下吾之辈已完成结构体系又俗话说青出于蓝而胜于蓝各个时期任务不同吾辈探索框架结构体系经历有限肯定发展...

框架柱抗震构造要求(框架柱抗震设计)

某现浇钢筋混凝土框架-剪力墙结构高层办公楼,抗震设防烈度为8度(0.2g),场地类别为Ⅱ类,抗震等级:框架二级,剪力墙一级,混凝土强度等级:框架柱及剪力墙C50,框架梁及楼板C35,纵向钢筋及箍筋均采...

梁的刚度、挠度控制(钢梁挠度过大会引起什么原因)

某办公楼为现浇钢筋混凝土框架结构,r0=1.0,混凝土强度等级C35,纵向钢筋采用HRB400,箍筋采用HPB300。其二层(中间楼层)的局部平面图和次梁L-1的计算简图如图1~3(Z)所示,其中,K...

死要面子!有钱做大玻璃窗,却没有钱做“柱和梁”,不怕房塌吗?

活久见,有钱做2层落地大玻璃窗,却没有钱做“柱子和圈梁”,这样的农村自建房,安全吗?最近刷到个魔幻施工现场,如下图,这栋5开间的农村自建房,居然做了2个全景落地窗仔细观察,这2个落地窗还是飘窗,为了追...

不是承重墙,物业也不让拆?话说装修就一定要拆墙才行么

最近发现好多朋友装修时总想拆墙“爆改”空间,别以为只要避开承重墙就能随便砸!我家楼上邻居去年装修,拆了阳台矮墙想扩客厅,结果物业直接上门叫停。后来才知道,这种配重墙拆了会让阳台承重失衡,整栋楼都可能变...

取消回复欢迎 发表评论: