pipeline in laravel

Reference: https://segmentfault.com/a/1190000010092899?utm_medium=hao.caibaojian.com&utm_source=hao.caibaojian.com&share_user=1030000000178452

The concept is easy to understand,but the code is so confused. Every pipe will be run in order . Also they will get the data given by the previous pipe.

let’s see how Laravel get the job done .

Before dispatching  the request to router , Laravel will go through all the middleware first. The request object will be passed through all the middleware. middleware array is in the App\Http\Kernel

reference: array_reduce
array_reduce(pipes,callablecallable,initial)this->carry() will return a closure . two parameters (stack,pipe)  will be provided into this closure function . stack is the return value of the previous pipe.item is the current pipe. And initial will be the firststack, it’s a closure function too.


The following is how the pipe iterations work.
let’s say  pipe = [middleware1, middleware2] array_reverse will reverse thepipe array,so pipe = [middleware2,middleware1] ====================first iteration===================stack = dispatchToRouter
pipe = middleware2 so the return value = return function (passable) use (dispatchToRouter ,middleware2) { //….}
Let’s look into detail. u can see the passable andstack will pass into the middleware  as parameters.
it’s time to find out how a middleware looks like.

it will run the next function at the end of the handle function, and thenext is equal to stack.so it means it will call thestack at the end.
so the execute order looks like this :
dispatchToRouter  <- -call–  middleware2
=================second iteration=====================
stack = a closure return by first iterationpipe = middleware1
the same as first iteration, the return value will be a closure.
and the execute order will be :
dispatchToRouter <–call–middleware2 <–call– middleware1
u may be confuse ,they are all closure. when will all these closure get called?
look carefully into the then() function.
the last iteration will return a closure. and the then() function  invoke the closure and pass the request object as a parameter.

that’s it!