💫 Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan / Vega 是一个用 PHP 编写的 CLI 模式 HTTP 网络框架,支持 Swoole、WorkerMan

Overview

Mix Vega

中文 | English

Vega is a CLI mode HTTP web framework written in PHP support Swoole, WorkerMan

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

Overview

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

推荐搭配以下数据库使用:

技术交流

知乎:https://www.zhihu.com/people/onanying
官方QQ群:284806582, 825122875 敲门暗号: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');

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');

设置中间件

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

$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();
    }
});

License

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

You might also like...
jojo, another http server written in PHP 8.0

جوجو | jojo جوجو، وب‌سروری در ابعاد جوجه برای کارهای کوچک داستان نوشتن جوجو وب‌سروری که تنظیمات مودم TP-link TD-8811 توی اتاقم رو serve میکنه اسمش mic

Hyperf instant messaging program based on swoole framework
Hyperf instant messaging program based on swoole framework

Hyperf instant messaging program based on swoole framework

Kit is a lightweight, high-performance and event-driven web services framework that provides core components such as config, container, http, log and route.

Kit What is it Kit is a lightweight, high-performance and event-driven web services framework that provides core components such as config, container,

Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

clue/reactphp-http-proxy Async HTTP proxy connector, tunnel any TCP/IP-based protocol through an HTTP CONNECT proxy server, built on top of ReactPHP.

Fast php framework written in c, built in php extension

Yaf - Yet Another Framework PHP framework written in c and built as a PHP extension. Requirement PHP 7.0+ (master branch)) PHP 5.2+ (php5 branch) Inst

FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Ruby on Rails.

FlyCubePHP FlyCubePHP is an MVC Web Framework developed in PHP and repeating the ideology and principles of building WEB applications, embedded in Rub

PHP Kafka client is used in PHP-FPM and Swoole. PHP Kafka client supports 50 APIs, which might be one that supports the most message types ever.

longlang/phpkafka Introduction English | 简体中文 PHP Kafka client is used in PHP-FPM and Swoole. The communication protocol is based on the JSON file in

一个极简高性能php框架,支持[swoole | php-fpm ]环境

One - 一个极简高性能php框架,支持[swoole | php-fpm ]环境 快 - 即使在php-fpm下也能1ms内响应请求 简单 - 让你重点关心用one做什么,而不是怎么用one 灵活 - 各个组件松耦合,可以灵活搭配使用,使用方法保持一致 原生sql可以和模型关系with搭配使用,

Releases(v3.0.28)
Owner
Mix PHP
OpenMix 开源组织研发的基于 Swoole 的新一代 PHP 高性能框架生态
Mix PHP
High performance HTTP Service Framework for PHP based on Workerman.

webman High performance HTTP Service Framework for PHP based on Workerman. Manual https://www.workerman.net/doc/webman Benchmarks https://www.techempo

walkor 1.3k Jan 2, 2023
swoole,easyswoole,swoole framework

EasySwoole - A High Performance Swoole Framework EasySwoole is a distributed, persistent memory PHP framework based on the Swoole extension. It was cr

null 4.6k Jan 2, 2023
Multi-process coroutine edition Swoole spider !! Learn about Swoole's network programming and the use of its related APIs

swoole_spider php bin/spider // Just do it !! Cache use Swoole\Table; use App\Table\Cache; $table = new Table(1<<20); // capacity size $table->column

null 3 Apr 22, 2021
A easy way to install your basic yii projetc, we have encrypt database password in phpfile, my class with alot funtions to help you encrypt and decrypt and our swoole server install just run ./yii swoole/start and be happy!

Yii 2 Basic Project Template with swoole and Modules Yii 2 Basic Project Template is a skeleton Yii 2 application best for rapidly creating small proj

null 3 Apr 11, 2022
swoole and golang ipc, use goroutine complete swoole coroutine

swoole and golang ipc demo swoole process module exec go excutable file as sider car, use goroutine complete swoole coroutine hub.php <?php require '

null 2 Apr 17, 2022
Socks5 proxy server written in Swoole PHP

php-socks This is a Socks5 proxy server implementation built with PHP & Swoole. To start the proxy server, clone this repo, run composer install to in

Nazmul Alam 3 Jan 23, 2022
Simple live support server with PHP Swoole Websocket and Telegram API

Telgraf Simple live support server with PHP Swoole Websocket and Telegram API. Usage Server Setup Clone repository with following command. git clone h

Adem Ali Durmuş 6 Dec 30, 2022
A server side alternative implementation of socket.io in PHP based on workerman.

phpsocket.io A server side alternative implementation of socket.io in PHP based on Workerman. Notice Only support socket.io v1.3.0 or greater. This pr

walkor 2.1k Jan 6, 2023
PHP Coroutine HTTP client - Swoole Humanization Library

PHP Coroutine HTTP client - Swoole Humanization Library

swlib 973 Dec 17, 2022
This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

This package provides a high performance HTTP server to speed up your Laravel/Lumen application based on Swoole.

Swoole Taiwan 3.9k Jan 8, 2023