Laravel pipeline

Laravel pipeline

介紹

就像其名稱管道一樣,我們可以把它想象成工廠的生產線。
生產線上的每一個環節就是一個管道,而每一個商品就是管道中傳遞的值。
按照環節順序對商品進行檢測,當有一個環節檢測不達標,則後續環節不會執行。
不達標的商品可能會放到一個回收環節,進行後續處理。

而在laravel中,中間件就扮演着管道中的一個個節點,對管道中的資源(HTTP請求)進行檢測,來決定是否放行。

laravel pipeline類的接口定義:


<?php

namespace Illuminate\Contracts\Pipeline;

use Closure;

interface Pipeline
{
    /**
     * 設置管道中的資源,也就是要經過中間件檢測的資源,在框架中傳遞的是Request對象
     *
     * @param  mixed  $traveler
     * @return $this
     */
    public function send($traveler);

    /**
     * 設置管道中的一個個節點,也就是一個個類,要經過的中間件列表
     *
     * @param  dynamic|array  $stops
     * @return $this
     */
    public function through($stops);

    /**
     * 設置執行節點中的哪個方法,默認是handle
     *
     * @param  string  $method
     * @return $this
     */
    public function via($method);

    /**
     * 上面的方法都是初始化,到這個then這裏纔是真正開始執行,原理主要使用了array_reduce、array_reverse函數。
     *
     * @param  \Closure  $destination
     * @return mixed
     */
    public function then(Closure $destination);
}


then函數的細節以後再深入理解,這裏推薦一篇對原理剖析的不錯的文章:https://www.cnblogs.com/guiyishanren/p/11150015.html

使用示例

比如有這樣一個場景,有一個物品,需要通過一些檢測並對其標記檢測結果。(但用的最多的還是中間件,其他場景基本沒用過)

$item = [
	'weight' => [
		'format' => 50,
		'verify' => null
	],
	'width' => [
		'format' => 100,
		'verify' => null
	],
	'height' => [
		'format' => 200,
		'verify' => null
	]
];

$pipes = [
    \App\Libs\BaseStandard\TestWeight::class,
    \App\Libs\BaseStandard\TestWidth::clas,
    \App\Libs\BaseStandard\TestHeight::class
];
$verify_result = app(Pipeline::class)
    ->send($item)
    ->through($pipes)
    ->via('check')
    ->then(function ($item) {
        return $item;
    });

輸出:

array:3 ["weight" => array:2 ["format" => 50
    "verify" => "success"
  ]
  "width" => array:2 ["format" => 100
    "verify" => "success"
  ]
  "height" => array:2 ["format" => 200
    "verify" => "success"
  ]
]
\App\Libs\BaseStandard\TestWeight類:

<?php
namespace App\Libs\BaseStandard;

use Closure;

class TestWeight
{
    public function check($item, Closure $next)
    {
        if ($item['weight']['format'] > 10) {
            $item['weight']['verify'] = 'success';
        }
        return $next($item);
    }
}

寫pipeline使用示例時參考了這篇文章,解釋的清晰明瞭,對我幫助很大:https://learnku.com/laravel/t/7543/pipeline-pipeline-design-paradigm-in-laravel

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章