2

Mix Vega

Vega is a CLI HTTP network framework written in PHP, supporting Swoole, WorkerMan

Overview

Vega is MixPHP V3+ (can be used independently), reference
Golang gin mux development, it contains a large number of functions for Web application processing (except database processing)
, Including: routing, rendering, parameter acquisition, middleware, file upload processing, etc.; it has strong compatibility in CLI mode, supports Swoole, WorkerMan, and supports Swoole's multiple process models.

It is recommended to use with the following databases:

Source address

Star won’t get lost, you can find it next time you use it

Technology Exchange

Know: https://www.zhihu.com/people/onanying
Official QQ group: 284806582 , 825122875 Knocking signal: vega

Installation

Need to install Swoole or WorkerMan
composer require mix/vega

Quick start

Swoole used in multi-process (asynchronous)

<?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 used in a single process (coroutine)

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

Used in 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();

Access test

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

Routing configuration

Configure Closure closure route

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

Configure callable routing

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

Configure routing variables

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

Configure multiple method

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

Routing prefix (grouping)

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

Parameter acquisition

Request parameter

Method namedescription
$ctx->param(string $key): stringGet routing parameters
$ctx->query(string $key): stringGet url parameters, including routing parameters
$ctx->defaultQuery(string $key, string $default): stringGet url parameters, default values can be configured
$ctx->getQuery(string $key): string or nullGet url parameter, can judge whether it exists
$ctx->postForm(string $key): stringGet post parameters
$ctx->defaultPostForm(string $key, string $default): stringGet post parameters, default values can be configured
$ctx->getPostForm(string $key): string or nullGet the post parameter, can judge whether it exists

Headers, Cookies, Uri ...

Method namedescription
$ctx->contentType(): stringRequest type
$ctx->header(string $key): stringRequest header
$ctx->cookie(string $name): stringcookies
$ctx->uri(): UriInterfaceFull uri
$ctx->rawData(): stringOriginal package data

Client IP

Method namedescription
$ctx->clientIP(): stringObtain the user's real IP from the reverse proxy
$ctx->remoteIP(): stringGet remote IP

Upload file processing

Method namedescription
$ctx->formFile(string $name): UploadedFileInterfaceGet the first file uploaded
$ctx->multipartForm(): UploadedFileInterface[]Get all uploaded files

File save

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

Request context

Some information needs to be saved in the request, such as session, JWT payload, etc.

Method namedescription
$ctx->set(string $key, $value): voidSettings
$ctx->get(string $key): mixed or nullGet value
$ctx->mustGet(string $key): mixed or throwsGet the value or throw an exception

Interrupt execution

abort executed, it will stop executing all subsequent codes, including middleware.

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

Response processing

Method namedescription
$ctx->status(int $code): voidSet status code
$ctx->setHeader(string $key, string $value): voidSet header
$ctx->setCookie(string $name, string $value, int $expire = 0, ...): voidSet cookie
$ctx->redirect(string $location, int $code = 302): voidRedirect

JSON request and output

Get JSON request data

$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 comes with a validity check, the following code is equivalent to the above

$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 processing

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

Set up middleware

Configure middleware for a route, you can configure multiple

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

Configure the global middleware, it will be executed even if the route is not matched

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

Pre-middleware

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

Post middleware

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

404 Custom

$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 global exception capture

$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 view rendering

Create view file foo.php

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

Configure the view path and respond to 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/


撸代码的乡下人
252 声望46 粉丝

我只是一个单纯爱写代码的人,不限于语言,不限于平台,不限于工具