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

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

ccwgpt 2024-10-10 04:55 32 浏览 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/

相关推荐

如何使用PIL生成验证码?(pi验证教程)

web项目中遇到使用验证码的情况有很多,进行介绍下使用PIL生成验证码的方法。安装开始安装PIL的过程确实麻烦各种问题层出不绝,不过不断深入后就没有这方面的困扰了:windows安装:直接安装Pil...

Python必学!3步解锁asyncio异步编程 性能直接狂飙10倍!

还在用传统同步代码被IO阻塞卡到崩溃?别当“代码苦行僧”了!Python的asyncio模块堪称异步编程的“开挂神器”,处理高并发任务就像开了涡轮增压!不管是网络爬虫、API接口开发还是文件批量处理,...

Tornado6+APScheduler/Celery打造并发异步动态定时任务轮询服务

定时任务的典型落地场景在各行业中都很普遍,比如支付系统中,支付过程中因为网络或者其他因素导致出现掉单、卡单的情况,账单变成了“单边账”,这种情况对于支付用户来说,毫无疑问是灾难级别的体验,明明自己付了...

Python学习怎么入门?附真实学习方法

Python技术在企业中应用的越来越广泛,因此企业对于Python方面专业人才的需求也越来越大,那对于之前对Python没有任何了解和接触的人而言,想要从零开始学习并不是一件容易的事情,接下来小U就为...

PySpider框架的使用(pyspider 教程)

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

大学计算机专业 学习Python学习路线图(最新版)

这是我刚开始学习python时的一套学习路线,从入门到上手。(不敢说精通,哈哈~)希望对大家有帮助哈~大家需要高清得完整python学习路线可以【文末有获取方式】【文末有获取方式】一、Python入门...

阿里巴巴打造的400集Python视频合集免费学起来,学完万物皆可爬

第一阶段Python入门章节1:Python入门章节2:编程基本概念章节3:序列章节4:控制语句章节5:函数章节6:面向对象编程第二阶段Python深入与提高章节1:异常处理章节2:游戏开发-坦克大...

Nginx Gunicorn在服务器中分别起什么作用

大部分人在gunicorn前面部署一层nginx的时候也的确没有想过为什么,他们只是觉得这样显得他们比较专业,而且幻想着加了一层nginx反向代理之后性能会有提升,恕我直言,请你们带上脑子,一个单纯的...

Python培训怎么学?Python基础技术总结!值得一看

Python培训如今越来越被更多人所接受,相比自学参加Python培训的好处也是显而易见,但Python毕竟属于后端编程开发的主流语言,其知识机构还是比较庞大的,那Python培训怎么学?以及Pyth...

使用Tornado部署Flask项目(tornado async)

Tornado不仅仅是一个WEB框架,也可以是一个WEB服务器。在Tornado中我们可以使用wsgi模块下的WSGIContainer类运行其他WSGI应用如:Fask,Bottle,Djang...

Python Web框架哪个好用?(python3 web框架)

  问:PythonWeb框架哪个好用?  答:  1.Django  Django是Python世界中最出名、最成熟的Web框架。Django功能全面,各模块之间结合紧密,(不讲其他的)Djang...

Vue3.0+Tornado6.1发布订阅模式打造异步非阻塞实时=通信聊天系统

“表达欲”是人类成长史上的强大“源动力”,恩格斯早就直截了当地指出,处在蒙昧时代即低级阶段的人类,“以果实、坚果、根作为食物;音节清晰的语言的产生是这一时期的主要成就”。而在网络时代人们的表达欲往往更...

Python开源项目合集(第三方平台)(python第三方开发工具)

wechat-python-sdk-wechat-python-sdk微信公众平台Python开发包http://wechat-python-sdk.readthedocs.org/,非官方...

IT界10倍高效学习法!用这种方式,一年学完清华大学四年的课程

有没有在某一个瞬间,让你放弃学编程刚开始学python时,我找了几十本国内外的python编程书籍学习后,我还是似懂非懂,那些书里面到处都是抽象的概念,复杂的逻辑,这样的书,对于专业开发者来说,在平常...

如何将Python算法模型注册成Spark UDF函数实现全景模型部署

背景Background对于算法业务团队来说,将训练好的模型部署成服务的业务场景是非常常见的。通常会应用于三个场景:部署到流式程序里,比如风控需要通过流式处理来实时监控。部署到批任务中部署成API服...

取消回复欢迎 发表评论: