這篇文章主要介紹了關於PHP管道外掛League\Pipeline的解析,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
Pipeline 設計模式
水管太長,只要有一處破了,就會漏水了,而且不利於複雜環境彎曲轉折使用。所以我們都會把水管分成很短的一節一節管道,然後最大化的讓管道大小作用不同,因地制宜,組裝在一起,滿足各種各樣的不同需求。
由此得出 Pipeline 的設計模式,就是將複雜冗長的流程 (processes) 截成各個小流程,小任務。每個最小量化的任務就可以重複使用,透過組裝不同的小任務,構成複雜多元的流程 (processes)。
最後將「輸入」引入管道,根據每個小任務對輸入進行操作 (加工、過濾),最後輸出滿足需要的結果。
今天主要學習學習「Pipeline」,順便推薦一個 PHP 外掛:league/pipeline
。
gulp
第一次知道「pipe」的概念,來自 gulp
的使用。
gulp
是基於NodeJS
的自動任務執行器,她能自動化地完成Javascript
、 sass
、less
等檔案的測試、檢查、合併、壓縮、格式化、瀏覽器自動刷新、部署檔案生成,並監聽檔案在變更後重複指定的這些步驟。在實現上,她借鑒了 Unix
作業系統的管道 (pipe) 思想,前一級的輸出,直接變成後一級的輸入,使得在操作上非常簡單。
var gulp = require('gulp'); var less = require('gulp-less'); var minifyCSS = require('gulp-csso'); var concat = require('gulp-concat'); var sourcemaps = require('gulp-sourcemaps'); 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' ]);
上面的兩個task
主要是將less
、所有js
檔案進行解析、壓縮、輸出等流程操作,然後儲存到對應的資料夾下;每一步操作的輸出就是下一步操作的輸入,猶如管道的流水一般。
IlluminatePipeline
Laravel 框架中的中介軟體,就是利用 Illuminate\Pipeline
來實現的,原本想寫寫我對「Laravel 中間件」原始碼的解讀,但發現網路上已經有很多貼文都有表述了,所以本文簡單說說如何使用Illuminate\Pipeline
。
寫個demo
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; }); }
對於該原始碼的分析,可以推薦看這篇文章,分析的挺透徹了:
Laravel Pipeline 元件的實作https://www.insp.top/article/realization-of-pipeline-component-for -laravel
LeaguePipeline
上面對gulp
和Illuminate\Pipeline
的簡單使用,只是告訴我們「Pipeline」應用比較廣泛。如果讓我們自己也寫一個類似的插件出來呢,我想應該也不會很難。
下面我拿 League\Pipeline
外掛來扒一扒它的原始碼,看如何實現的。
簡述
This package provides a plug and play implementation of the Pipeline Pattern. It's an architectural pattern which encapsulates sequential processes. When used, it allows you to mixit and match operation, and pipelines, to create new execution chains. The pipeline pattern is often compared to a production line, where each stage performs a certain operation on a given payload/subject. Stages can reject. Stagesd on a given payment/subject. Stages can reject. Stagesman or. the payload.If you find yourself passing results from one function to another to complete a series of tasks on a given subject, you might want to convert it into a pipeline.
. thephpleague.com/
安裝外掛
composer require league/pipeline
寫個demo
use League\Pipeline\Pipeline; // 创建两个闭包函数 $pipe1 = function ($payload) { return $payload + 1; }; $pipe2 = function ($payload) { return $payload * 3; }; $route->map( 'GET', '/demo', function (ServerRequestInterface $request, ResponseInterface $response ) use ($service, $pipe1, $pipe2) { $params = $request->getQueryParams(); // 正常使用 $pipeline1 = (new Pipeline) ->pipe($pipe1) ->pipe($pipe2); $callback1 = $pipeline1->process($params['data']); $response->getBody()->write("<h1 id="正常使用">正常使用</h1>"); $response->getBody()->write("<p>结果:$callback1</p>"); // 使用魔术方法 $pipeline2 = (new Pipeline()) ->pipe($pipe1) ->pipe($pipe2); $callback2 = $pipeline2($params['data']); $response->getBody()->write("<h1 id="使用魔术方法">使用魔术方法</h1>"); $response->getBody()->write("<p>结果:$callback2</p>"); // 使用 Builder $builder = new PipelineBuilder(); $pipeline3 = $builder ->add($pipe1) ->add($pipe2) ->build(); $callback3 = $pipeline3($params['data']); $response->getBody()->write("<h1 id="使用-Builder">使用 Builder</h1>"); $response->getBody()->write("<p>结果:$callback3</p>"); return $response; } );
執行結果
解讀原始程式碼
就這幾個檔案這個外掛程式:
PipelineInterface
<?php declare(strict_types=1); namespace League\Pipeline; interface PipelineInterface extends StageInterface { /** * Create a new pipeline with an appended stage. * * @return static */ public function pipe(callable $operation): PipelineInterface; } interface StageInterface { /** * Process the payload. * * @param mixed $payload * * @return mixed */ public function __invoke($payload); }
該介面主要利用鍊式程式設計的思想,不斷添加管道“pipe”,然後增加一個魔術方法,來讓傳入的參數運作起來。
先看看這個魔術方法的作用:
mixed __invoke ([ $... ] )
当尝试以调用函数的方式调用一个对象时,__invoke() 方法会被自动调用。如:
<?php class CallableClass { function __invoke($x) { var_dump($x); } } $obj = new CallableClass; $obj(5); var_dump(is_callable($obj)); ?>
返回结果:
int(5) bool(true)
Pipeline
<?php declare(strict_types=1); 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); } }
其中核心类 Pipeline
的作用主要就是两个:
添加组装各个管道「pipe」;
组装后,引水流动,执行 process($payload),输出结果。
Processor
接好各种管道后,那就要「引水入渠」了。该插件提供了两个基础执行类,比较简单,直接看代码就能懂。
// 按照 $stages 数组顺利,遍历执行管道方法,再将结果传入下一个管道,让「水」一层层「流动」起来 class FingersCrossedProcessor implements ProcessorInterface { public function process($payload, callable ...$stages) { foreach ($stages as $stage) { $payload = $stage($payload); } return $payload; } } // 增加一个额外的「过滤网」,经过每个管道后的结果,都需要 check,一旦满足则终止,直接输出结果。 class InterruptibleProcessor implements ProcessorInterface { /** * @var callable */ private $check; public function __construct(callable $check) { $this->check = $check; } public function process($payload, callable ...$stages) { $check = $this->check; foreach ($stages as $stage) { $payload = $stage($payload); if (true !== $check($payload)) { return $payload; } } return $payload; } } interface ProcessorInterface { /** * Process the payload using multiple stages. * * @param mixed $payload * * @return mixed */ public function process($payload, callable ...$stages); }
我们完全也可以利用该接口,实现我们的方法来组装管道和「过滤网」。
PipelineBuilder
最后提供了一个 Builder,这个也很好理解:
class PipelineBuilder implements PipelineBuilderInterface { /** * @var callable[] */ private $stages = []; /** * @return self */ public function add(callable $stage): PipelineBuilderInterface { $this->stages[] = $stage; return $this; } public function build(ProcessorInterface $processor = null): PipelineInterface { return new Pipeline($processor, ...$this->stages); } } interface PipelineBuilderInterface { /** * Add an stage. * * @return self */ public function add(callable $stage): PipelineBuilderInterface; /** * Build a new Pipeline object. */ public function build(ProcessorInterface $processor = null): PipelineInterface; }
总结
无论是对不同技术的横向理解,还是基于 Laravel 或者某些开源插件,我们都能学习到技术之上的通用原理和方法。再将这些原理和方法反作用于我们的实际代码开发中。
最近闲来没事,自己参考 Laravel 去写个简易框架,也将League\Pipeline
引入到框架中使用。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
关于利用Vue-laravel前端和后端分离写一个博客的方法
以上是關於PHP管道插件 League\Pipeline的解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

PHP用於構建動態網站,其核心功能包括:1.生成動態內容,通過與數據庫對接實時生成網頁;2.處理用戶交互和表單提交,驗證輸入並響應操作;3.管理會話和用戶認證,提供個性化體驗;4.優化性能和遵循最佳實踐,提升網站效率和安全性。

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。

在PHP中使用預處理語句和PDO可以有效防範SQL注入攻擊。 1)使用PDO連接數據庫並設置錯誤模式。 2)通過prepare方法創建預處理語句,使用佔位符和execute方法傳遞數據。 3)處理查詢結果並確保代碼的安全性和性能。

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP可以輕鬆創建互動網頁內容。 1)通過嵌入HTML動態生成內容,根據用戶輸入或數據庫數據實時展示。 2)處理表單提交並生成動態輸出,確保使用htmlspecialchars防XSS。 3)結合MySQL創建用戶註冊系統,使用password_hash和預處理語句增強安全性。掌握這些技巧將提升Web開發效率。

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SublimeText3 Linux新版
SublimeText3 Linux最新版

Dreamweaver CS6
視覺化網頁開發工具

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中