Home  >  Article  >  PHP Framework  >  Learn about Pipeline in Laravel in one article

Learn about Pipeline in Laravel in one article

青灯夜游
青灯夜游forward
2022-11-16 20:49:571701browse

This article will take you to understand the Pipeline in Laravel and talk about the pipeline design paradigm. I hope it will be helpful to you!

Learn about Pipeline in Laravel in one article

In general, by using pipes in Laravel, you can smoothly pass an object between several classes to perform any type of task. After all tasks are executed, the result value will be returned.

Next, you can learn more about Laravel pipelines.

Regarding the way pipeline is run, the most obvious example is actually one of the most commonly used components in the framework itself. Yes, I am talking about middleware.

Middleware provides a convenient mechanism for filtering HTTP requests entering the application.

A basic middleware should look like this:

<?php
namespace App\Http\Middleware;
use Closure;
class TestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Here you can add your code
        return $next($request);
    }
}

These "middleware" are actually pipelines, through which requests are sent to perform any required tasks. Here, you can check whether the request is an HTTP request, whether it is a JSON request, whether there is authenticated user information, etc.

If you want to take a quick look at the Illuminate\Foundation\Http\Kernel class, you will see how to use a new instance of the Pipeline class to execute middleware.

/**
  * Send the given request through the middleware / router.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
protected function sendRequestThroughRouter($request)
{
    $this->app->instance(&#39;request&#39;, $request);
    Facade::clearResolvedInstance(&#39;request&#39;);
    $this->bootstrap();
    return (new Pipeline($this->app))
                    ->send($request)
                    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
    ->then($this->dispatchToRouter());
}

You can see something similar in the code: a new pipe that sends the request through the middleware list, and then sends the route.

Don’t worry if this seems a little overwhelming to you. Let us try to clarify this concept using the following example.

Handling multi-tasking running class

Let's look at a scenario. Let's say you set up a forum where people can post and comment. However, your users request that you automatically remove tags or edit tags on every piece of content as they are created.

What you are asked to do at this time is as follows:

  • Replace the link tag with plain text;

  • Replace the link tag with "* "Replace sensitive words;

  • Remove script tags completely from content.

Maybe you will eventually create classes to handle these "tasks".

$pipes = [
    RemoveBadWords::class
    ReplaceLinkTags::class
    RemoveScriptTags::class
];

What we want to do is pass the given "content" to each task and then return the result to the next task. We can use pipeline to do this.

<?php

public function create(Request $request)
{
    $pipes = [
        RemoveBadWords::class,
        ReplaceLinkTags::class,
        RemoveScriptTags::class
    ];
    $post = app(Pipeline::class)
        ->send($request->content)
        ->through($pipes)
        ->then(function ($content) {
            return Post::create([&#39;content&#39; => &#39;content&#39;]);
        });
    // return any type of response
}

Each "task" class should have a "handle" method to perform operations. Maybe having unified constraints for each class is a good choice:

<?php

namespace App;

use Closure;

interface Pipe
{
    public function handle($content, Closure $next);
}

Naming is a difficult thing ¯_(ツ)_/¯

<?php

namespace App;

use Closure;

class RemoveBadWords implements Pipe
{
    public function handle($content, Closure $next)
    {
        // Here you perform the task and return the updated $content
        // to the next pipe
        return  $next($content);
    }
}

The method used to perform the task should receive two parameters. The first parameter is the qualified object, and the second parameter is the next closure (anonymous function) that will be taken over after the current operation is processed.

You can use a custom method name instead of "handle". Then you need to specify the method name to be used by the pipeline, such as:

app(Pipeline::class)
 ->send($content)
 ->through($pipes)
 ->via(&#39;customMethodName&#39;) // <---- This one :)
 ->then(function ($content) {
     return Post::create([&#39;content&#39; => $content]);
 });

What is the final effect?

submitted The content will be processed by each $pipes, and the processed results will be stored.

$post = app(Pipeline::class)
    ->send($request->all())
    ->through($pipes)
    ->then(function ($content) {
        return Post::create([&#39;content&#39; => $content]);
    });

Conclusion

Remember, there are many ways to solve this type of problem. As for how to choose, it depends on your own choice. Just know that you can use this tool when needed. I hope this example gave you a better understanding of "Laravel pipelines" and how to use them. If you want to know or learn more, you can check out Laravel's API documentationlaravel.com/api/5.4/Illuminate/Pip...

Original address: https: //medium.com/@jeffochoa/understanding-laravel-pipelines-a7191f75c351

Translation address: https://learnku.com/laravel/t/7543/pipeline-pipeline-design-paradigm-in-laravel

[Related recommendations: laravel video tutorial]

The above is the detailed content of Learn about Pipeline in Laravel in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete