<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          MixVegaCLI HTTP 網(wǎng)絡框架

          聯(lián)合創(chuàng)作 · 2023-09-20 01:50

          Vega 是一個用 PHP 編寫的 CLI 模式 HTTP 網(wǎng)絡框架,支持 Swoole、WorkerMan、FPM、CLI-Server

          概述

          Vega 是 MixPHP V3+ 內(nèi)置的最核心的組件 (可獨立使用),參考 golang gin mux 開發(fā),它包含 Web 應用處理的大量功能 (數(shù)據(jù)庫處理除外) ,包括:路由、渲染、參數(shù)獲取、中間件、文件上傳、靜態(tài)文件處理等;具有 CLI 模式下強大的兼容性,同時支持 Swoole、WorkerMan、FPM、CLI-Server, 并且支持 Swoole 的多種進程模型與協(xié)程。

          推薦搭配以下數(shù)據(jù)庫使用:

          推薦文章:

          技術交流

          知乎:https://www.zhihu.com/people/onanying
          官方QQ群:284806582 , 825122875 敲門暗號:vega

          安裝

          需先安裝 Swoole 或者 WorkerMan

          composer require mix/vega

          快速開始

          • Swoole 多進程 (異步) 中使用
          <?php
          require __DIR__ . '/vendor/autoload.php';
          
          $vega = new Mix\Vega\Engine();
          $vega->handle('/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->set([
              'worker_num' => 4,
          ]);
          $http->start();

          開啟多進程協(xié)程

          $http->on('Request', $vega->handler());
          $http->on('WorkerStart', function ($server, $workerId) {
              // 協(xié)程初始化
              // 比如:啟動 mix/database mix/redis 的連接池
          });
          $http->set([
              'enable_coroutine' => true,
              'worker_num' => 4,
          ]);
          php swoole.php
          • Swoole 單進程 (協(xié)程) 中使用
          <?php
          require __DIR__ . '/vendor/autoload.php';
          
          Swoole\Coroutine\run(function () {
              $vega = new Mix\Vega\Engine();
              $vega->handle('/hello', function (Mix\Vega\Context $ctx) {
                  $ctx->string(200, 'hello, world!');
              })->methods('GET');
              
              $server = new Swoole\Coroutine\Http\Server('0.0.0.0', 9502, false);
              $server->handle('/', $vega->handler());
              $server->start();
          });
          php swooleco.php
          • WorkerMan 中使用
          <?php
          require __DIR__ . '/vendor/autoload.php';
          
          $vega = new Mix\Vega\Engine();
          $vega->handle('/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();
          php wokerman.php start
          • PHP-FPM 中使用

          在 nginx 配置 rewrite 重寫到 index.php

          <?php
          require __DIR__ . '/vendor/autoload.php';
          
          $vega = new Mix\Vega\Engine();
          $vega->handle('/hello', function (Mix\Vega\Context $ctx) {
              $ctx->string(200, 'hello, world!');
          })->methods('GET');
          return $vega->run();

          這個內(nèi)置的Web服務器主要用于本地開發(fā)使用,不可用于線上產(chǎn)品環(huán)境。

          <?php
          require __DIR__ . '/vendor/autoload.php';
          
          $vega = new Mix\Vega\Engine();
          $vega->handle('/hello', function (Mix\Vega\Context $ctx) {
              $ctx->string(200, 'hello, world!');
          })->methods('GET');
          return $vega->run();
          php -S localhost:8000 router.php
          • 訪問測試
          % curl http://127.0.0.1:9501/hello
          hello, world!

          路由配置

          配置 Closure 閉包路由

          $vega = new Mix\Vega\Engine();
          $vega->handle('/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->handle('/hello', [new Hello(), 'index'])->methods('GET');

          配置路由變量

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

          配置多個 method

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

          路由前綴 (分組)

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

          參數(shù)獲取

          請求參數(shù)

          方法名稱 描述
          $ctx->request: ServerRequestInterface 符合PSR的請求對象
          $ctx->response: ResponseInterface 符合PSR的響應對象
          ctx?>param(stringctx?>param(stringkey): string 獲取路由參數(shù)
          ctx?>query(stringctx?>query(stringkey): string 獲取url參數(shù),包含路由參數(shù)
          ctx?>defaultQuery(stringctx?>defaultQuery(stringkey, string $default): string 獲取url參數(shù),可配置默認值
          ctx?>getQuery(stringctx?>getQuery(stringkey): string or null 獲取url參數(shù), 可判斷是否存在
          ctx?>postForm(stringctx?>postForm(stringkey): string 獲取post參數(shù)
          ctx?>defaultPostForm(stringctx?>defaultPostForm(stringkey, string $default): string 獲取post參數(shù),可配置默認值
          ctx?>getPostForm(stringctx?>getPostForm(stringkey): string or null 獲取post參數(shù),可判斷是否存在

          Headers, Cookies, Uri ...

          方法名稱 描述
          $ctx->contentType(): string 請求類型
          ctx?>header(stringctx?>header(stringkey): string 請求頭
          ctx?>cookie(stringctx?>cookie(stringname): string cookies
          $ctx->uri(): UriInterface 完整uri
          $ctx->rawData(): string 原始包數(shù)據(jù)

          客戶端IP

          方法名稱 描述
          $ctx->clientIP(): string 從反向代理獲取用戶真實IP
          $ctx->remoteIP(): string 獲取遠程IP

          上傳文件處理

          方法名稱 描述
          ctx?>formFile(stringctx?>formFile(stringname): UploadedFileInterface 獲取上傳的第一個文件
          $ctx->multipartForm(): UploadedFileInterface[] 獲取上傳的全部文件

          文件保存

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

          請求上下文

          請求當中需要保存一些信息,比如:會話、JWT載荷等。

          方法名稱 描述
          ctx?>set(stringctx?>set(stringkey, $value): void 設置值
          ctx?>get(stringctx?>get(stringkey): mixed or null 獲取值
          ctx?>mustGet(stringctx?>mustGet(stringkey): mixed or throws 獲取值或拋出異常

          中斷執(zhí)行

          abort 執(zhí)行后,會停止執(zhí)行后面的全部代碼,包括中間件。

          方法名稱 描述
          $ctx->abort(): void 中斷,需自行處理響應
          ctx?>abortWithStatus(intctx?>abortWithStatus(intcode): void 中斷并響應狀態(tài)碼
          ctx?>abortWithStatusJSON(intctx?>abortWithStatusJSON(intcode, $data): void 中斷并響應JSON
          $vega = new Mix\Vega\Engine();
          $vega->handle('/users/{id}', function (Mix\Vega\Context $ctx) {
              if (true) {
                  $ctx->string(401, 'Unauthorized');
                  $ctx->abort();
              }
              $ctx->string(200, 'hello, world!');
          })->methods('GET');

          響應處理

          方法名稱 描述
          ctx?>status(intctx?>status(intcode): void 設置狀態(tài)碼
          ctx?>setHeader(stringctx?>setHeader(stringkey, string $value): void 設置header
          ctx?>setCookie(stringctx?>setCookie(stringname, string value,intvalue,intexpire = 0, ...): void 設置cookie
          ctx?>redirect(stringctx?>redirect(stringlocation, int $code = 302): void 重定向

          JSON 請求與輸出

          獲取 JSON 請求數(shù)據(jù)

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

          HTML 視圖渲染

          創(chuàng)建視圖文件 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->handle('/html', function (Mix\Vega\Context $ctx) {
              $ctx->HTML(200, 'foo', [
                  'id' => 1000,
                  'name' => '小明',
                  'friends' => [
                      '小花',
                      '小紅'
                  ]
              ]);
          })->methods('GET');

          靜態(tài)文件處理

          基于 sendfile 零拷貝,不支持在 PHP-FPM 中使用

          $vega = new Mix\Vega\Engine();
          $vega->static('/static', '/data/project/public/static');
          $vega->staticFile('/favicon.ico', '/data/project/public/favicon.ico');

          設置中間件

          給某個路由配置中間件,可配置多個

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

          配置全局中間件,即便沒有匹配到路由也會執(zhí)行

          $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) {
                  if ($ex instanceof Mix\Vega\Abort || $ex instanceof Mix\Vega\Exception\NotFoundException) {
                      throw $ex;
                  }
                  $ctx->string(500, 'New 500 response');
                  $ctx->abort();
              }
          });

          License

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

          瀏覽 19
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          編輯 分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          編輯 分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  草草视频免费观看 | 大香蕉伊人视频 | 丁香五月激情六月 | 成人性生活无码视频 | 日韩大香蕉视频 |