search
HomePHP FrameworkLaravelLearn about Pipeline in Laravel in one article

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. If there is any infringement, please contact admin@php.cn delete
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)