佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > PHP Pipeline 實(shí)現(xiàn)中間件的示例代碼

PHP Pipeline 實(shí)現(xiàn)中間件的示例代碼

熱門標(biāo)簽:銀行業(yè)務(wù) 團(tuán)購(gòu)網(wǎng)站 Mysql連接數(shù)設(shè)置 阿里云 服務(wù)器配置 電子圍欄 科大訊飛語(yǔ)音識(shí)別系統(tǒng) Linux服務(wù)器

Pipeline 設(shè)計(jì)模式

水管太長(zhǎng),只要有一處破了,就會(huì)漏水了,而且不利于復(fù)雜環(huán)境彎曲轉(zhuǎn)折使用。所以我們都會(huì)把水管分成很短的一節(jié)一節(jié)管道,然后最大化的讓管道大小作用不同,因地制宜,組裝在一起,滿足各種各樣的不同需求。

由此得出 Pipeline 的設(shè)計(jì)模式,就是將復(fù)雜冗長(zhǎng)的流程 (processes) 截成各個(gè)小流程,小任務(wù)。每個(gè)最小量化的任務(wù)就可以復(fù)用,通過(guò)組裝不同的小任務(wù),構(gòu)成復(fù)雜多樣的流程 (processes)。

最后將「輸入」引入管道,根據(jù)每個(gè)小任務(wù)對(duì)輸入進(jìn)行操作 (加工、過(guò)濾),最后輸出滿足需要的結(jié)果。

你可以拿koa的中間件機(jī)制來(lái)做參考 ,也就是我們常說(shuō)的削洋蔥思路

在前端里早期有一個(gè)工程打包工具gulp寫法就更能體現(xiàn)pipeline

gulp.task('css', function(){
 return gulp.src('client/templates/*.less')
  .pipe(less())
  .pipe(minifyCSS())
  .pipe(gulp.dest('build/css'))
});

gulp.task('js', function(){
 return gulp.src('client/javascript/*.js')
  .pipe(sourcemaps.init())
  .pipe(concat('app.min.js'))
  .pipe(sourcemaps.write())
  .pipe(gulp.dest('build/js'))
});

gulp.task('default', [ 'html', 'css', 'js' ]);

IlluminatePipeline

Laravel 框架中的中間件,就是利用 Illuminate\Pipeline 來(lái)實(shí)現(xiàn)的,本來(lái)想寫寫我對(duì) 「Laravel 中間件」源碼的解讀,但發(fā)現(xiàn)網(wǎng)上已經(jīng)有很多帖子都有表述了,所以本文就簡(jiǎn)單說(shuō)說(shuō)如何使用 Illuminate\Pipeline。

public function demo(Request $request)
{
  $pipe1 = function ($payload, Closure $next) {
    $payload = $payload + 1;
    return $next($payload);
  };

  $pipe2 = function ($payload, Closure $next) {
    $payload = $payload * 3;
    return $next($payload);
  };

  $data = $request->input('data', 0);

  $pipeline = new Pipeline();

  return $pipeline
    ->send($data)
    ->through([$pipe1, $pipe2])
    ->then(function ($data) {
      return $data;
    });
}

今天主要學(xué)習(xí)學(xué)習(xí)「Pipeline」,順便推薦一個(gè) PHP 插件:league/pipeline

composer require league/pipeline

使用起來(lái)也很方便

use League\Pipeline\Pipeline;

class TimesTwoStage
{
  public function __invoke($payload)
  {
    return $payload * 2;
  }
}

class AddOneStage
{
  public function __invoke($payload)
  {
    return $payload + 1;
  }
}

$pipeline = (new Pipeline)
  ->pipe(new TimesTwoStage)
  ->pipe(new AddOneStage);

// Returns 21
$pipeline->process(10);

接下來(lái)我們添加FastRouter在我的項(xiàng)目中使用。

上面的代碼修改成這樣

我們接下來(lái)看看 RespondJson 里做了什么.

?php
namespace Platapps\Middlewares;
class RespondJson
{
  public function __invoke($payload)
  {
    header('Content-type:text/json');
    return $payload;
  }
}

就簡(jiǎn)單的加了個(gè) header

我們?cè)囋嚢炎⑨尩揭粋€(gè)渠道

我們?cè)俅卧L問(wèn)的時(shí)候就變成

當(dāng)然這是很簡(jiǎn)單的中間件,這種中間件遠(yuǎn)遠(yuǎn)不夠,這里是核心代碼,可以去這里看看,也比較簡(jiǎn)單。

我們最終需要修改pipe這個(gè)方法

namespace League\Pipeline;

class Pipeline implements PipelineInterface
{
  /**
   * @var callable[]
   */
  private $stages = [];

  /**
   * @var ProcessorInterface
   */
  private $processor;

  public function __construct(ProcessorInterface $processor = null, callable ...$stages)
  {
    $this->processor = $processor ?? new FingersCrossedProcessor;
    $this->stages = $stages;
  }

  public function pipe(callable $stage): PipelineInterface
  {
    $pipeline = clone $this;
    $pipeline->stages[] = $stage;

    return $pipeline;
  }

  public function process($payload)
  {
    return $this->processor->process($payload, ...$this->stages);
  }

  public function __invoke($payload)
  {
    return $this->process($payload);
  }
}

這么多框架里面我這里建議拿Tp6的來(lái)做參考,功能還算夠用。

?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin 448901948@qq.com>
// +----------------------------------------------------------------------
namespace think;

use Closure;
use Exception;
use Throwable;

class Pipeline
{
  protected $passable;

  protected $pipes = [];

  protected $exceptionHandler;

  /**
   * 初始數(shù)據(jù)
   * @param $passable
   * @return $this
   */
  public function send($passable)
  {
    $this->passable = $passable;
    return $this;
  }

  /**
   * 調(diào)用棧
   * @param $pipes
   * @return $this
   */
  public function through($pipes)
  {
    $this->pipes = is_array($pipes) ? $pipes : func_get_args();
    return $this;
  }

  /**
   * 執(zhí)行
   * @param Closure $destination
   * @return mixed
   */
  public function then(Closure $destination)
  {
    $pipeline = array_reduce(
      array_reverse($this->pipes),
      $this->carry(),
      function ($passable) use ($destination) {
        try {
          return $destination($passable);
        } catch (Throwable | Exception $e) {
          return $this->handleException($passable, $e);
        }
      });

    return $pipeline($this->passable);
  }

  /**
   * 設(shè)置異常處理器
   * @param callable $handler
   * @return $this
   */
  public function whenException($handler)
  {
    $this->exceptionHandler = $handler;
    return $this;
  }

  protected function carry()
  {
    return function ($stack, $pipe) {
      return function ($passable) use ($stack, $pipe) {
        try {
          return $pipe($passable, $stack);
        } catch (Throwable | Exception $e) {
          return $this->handleException($passable, $e);
        }
      };
    };
  }

  /**
   * 異常處理
   * @param $passable
   * @param $e
   * @return mixed
   */
  protected function handleException($passable, Throwable $e)
  {
    if ($this->exceptionHandler) {
      return call_user_func($this->exceptionHandler, $passable, $e);
    }
    throw $e;
  }
}

這種寫法有什么好?

其實(shí)就好就好在,你在處理一個(gè)請(qǐng)求的過(guò)程中,分配任務(wù)的時(shí)候,在處理的過(guò)程,每個(gè)中間的人,只要做自己處理的請(qǐng)求和結(jié)果還有請(qǐng)求即可。讓當(dāng)數(shù)據(jù)到達(dá)Controller里的時(shí)候,顯示業(yè)務(wù)邏輯的時(shí)候更加強(qiáng)大

到此這篇關(guān)于PHP Pipeline 實(shí)現(xiàn)中間件的示例代碼的文章就介紹到這了,更多相關(guān)PHP Pipeline 中間件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Golang之casbin權(quán)限管理的實(shí)現(xiàn)
  • thinkphp5.1的model模型自動(dòng)更新update_time字段實(shí)例講解
  • Thinkphp5.1獲取項(xiàng)目根目錄以及子目錄路徑的方法實(shí)例講解
  • Thinkphp使用Zxing擴(kuò)展庫(kù)解析二維碼內(nèi)容圖文講解
  • laravel與thinkphp之間的區(qū)別與優(yōu)缺點(diǎn)
  • ThinkPHP的標(biāo)簽制作實(shí)例講解
  • thinkphp的鉤子的兩種配置和兩種調(diào)用方法
  • ThinkPHP6.0如何利用自定義驗(yàn)證規(guī)則規(guī)范的實(shí)現(xiàn)登陸
  • 如何使用Casbin作為ThinkPHP的權(quán)限控制中間件

標(biāo)簽:蚌埠 棗莊 廣元 衢州 萍鄉(xiāng) 衡水 江蘇 大理

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP Pipeline 實(shí)現(xiàn)中間件的示例代碼》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    尉犁县| 玉林市| 大埔县| 梨树县| 宁陵县| 桂林市| 莆田市| 清水河县| 邓州市| 洪洞县| 韶关市| 通城县| 黄骅市| 海宁市| 新宁县| 班戈县| 江永县| 邵阳县| 天等县| 岑溪市| 岳阳市| 宝坻区| 富川| 福州市| 隆回县| 阳城县| 察雅县| 敦化市| 察哈| 莎车县| 墨玉县| 图们市| 万年县| 古丈县| 分宜县| 广西| 阿尔山市| 宝鸡市| 信阳市| 越西县| 北辰区|