搜尋
首頁php框架LaravelLaravel使用管道處理名字, 實現統一處理

##上「使用中的管道」的資料中使用範例,並希望為需要的朋友提供幫助!

從程式碼的角度介紹管道的實際使用方式。有關管道的說明,網路上已有較多的篇幅介紹,自行查閱。

本篇部落格是使用管道處理名字, 實現統一處理的目的。

Laravel使用管道處理名字, 實現統一處理背景:

目前能找到的使用管道的介紹也很多,大多停留在對其介紹和引導,真正的深入到程式碼的部分不多。根據介紹,使用管道也有一定的阻礙,這裡分享一篇關於使用管道的詳細的程式碼實例,僅供參考。

本篇介紹是自己真實使用的過程的程式碼摘錄,親自測試,真實可用。只為拋磚引玉,不喜勿噴。


一、控制器

路由器部分

Route::get('/pipe', ['as'=>'pipe', 'uses'=>'PipeController@index']);
控製程式碼
<?php

namespace App\Http\Controllers;

use App\Pipes\LeftWords;
use App\Pipes\RightWords;
use App\Pipes\BothSidesWords;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;
use App\User;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;

class PipeController extends Controller
{
    /* 定义管道
     *
     * 第一步处理
     * 第二部处理
     * 第三部处理
     * */
    protected $pipes = [
        LeftWords::class,
        RightWords::class,
        BothSidesWords::class,
    ];
    // 首页
    public function index(Request $request){
        $name = $request->input(&#39;name&#39;);
        // $name = Str::random(10);

        return app(Pipeline::class)
            ->send($name)
            ->through($this->pipes)
            ->then(function ($content) {
                return User::create([
                    &#39;name&#39; => $content,
                    &#39;email&#39;=>Str::random(10).&#39;@gmail.com&#39;,
                    &#39;password&#39;=>Hash::make(&#39;password&#39;),
                ]);
            });
    }
}

二、管道部分

目錄結構如下:

├─app
│  │  User.php
│  ├─Http
│  │  ...│  │
│  ├─Models
│  │  ...│  │
│  ├─Pipes
│  │  │  BothSidesWords.php
│  │  │  LeftWords.php
│  │  │  RightWords.php
│  │  │
│  │  └─Contracts
│  │          PipeContracts.php

interface

的程式碼
    路徑
  • app/Pipes/Contracts/Pipe.php

    下的程式碼如下:

     <?php
     namespace App\Pipes\Contracts;
    
     use Closure;
    
     interface PipeContracts
     {
         public function handle($body, Closure $next);
     }

    三個管道的類別的程式碼
LeftWords.php
    的程式碼

  •   <?php  namespace App\Pipes;
    
     use App\Pipes\Contracts\PipeContracts;
     use Closure;
    
     class LeftWords implements PipeContracts{
         public function handle($body, Closure $next)
         {
             // TODO: Implement handle() method.
    
             $body = &#39;left-&#39;.$body;
    
             return $next($body);
         }
     }
    LeftWords.php的程式碼
  <?php  namespace App\Pipes;

 use App\Pipes\Contracts\PipeContracts;
 use Closure;

 class RightWords implements PipeContracts{
     public function handle($body, Closure $next)
     {
         // TODO: Implement handle() method.

         $body = $body.&#39;-right&#39;;

         return $next($body);
     }
 }

BothSidesWords.php的程式碼

  <?php  namespace App\Pipes;

 use App\Pipes\Contracts\PipeContracts;
 use Closure;

 class BothSidesWords implements PipeContracts{
     public function handle($body, Closure $next)
     {
         // TODO: Implement handle() method.

         $body = &#39;[&#39;.$body.&#39;]&#39;;

         return $next($body);
     }
 }
這裡我們使用管道預設的方法

handle ,你可以自訂方法名稱。像下面這樣定義myHandleMethod

為處理方法名稱。

return app(Pipeline::class)
        ->send($name)
        ->through($this->pipes)
        ->via('myHandleMethod')
        ->then(function ($content) {
            return User::create([
                'name' => $content,
                'email'=>Str::random(10).'@gmail.com',
                'password'=>Hash::make('password'),
            ]);
        });
你這樣定義後,修改你的interface,同時修改你的實作類別即可。

三、結果說明

造訪表內部,有資料儲存成功。

{
"name": "[left-lisa-right]",
"email": "3riSrDuBFv@gmail.com",
"updated_at": "2020-09-05T05:57:14.000000Z",
"created_at": "2020-09-05T05:57:14.000000Z",
"id": 15
}

以上是Laravel使用管道處理名字, 實現統一處理的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:learnku。如有侵權,請聯絡admin@php.cn刪除
包容的幻想:解決偏遠工作中的孤立和孤獨感包容的幻想:解決偏遠工作中的孤立和孤獨感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用於全堆棧開發:綜合指南Laravel用於全堆棧開發:綜合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

視頻會議攤牌:為遠程會議選擇正確的平台視頻會議攤牌:為遠程會議選擇正確的平台Apr 25, 2025 am 12:26 AM

選擇視頻會議平台的關鍵因素包括用戶界面、安全性和功能。 1)用戶界面應直觀,如Zoom。 2)安全性需重視,MicrosoftTeams提供端到端加密。 3)功能需匹配需求,GoogleMeet適合簡短會議,CiscoWebex提供高級協作工具。

哪些數據庫版本與最新的Laravel兼容?哪些數據庫版本與最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10與MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。這些版本選擇是因為它們支持Laravel的ORM功能,如MySQL5.7的JSON數據類型,提升了查詢和存儲效率。

將Laravel用作全棧框架的好處將Laravel用作全棧框架的好處Apr 25, 2025 am 12:24 AM

Laravelisanexcellentchoiceforfull-stackdevelopmentduetoitsrobustfeaturesandeaseofuse.1)ItsimplifiescomplextaskswithitsmodernPHPsyntaxandtoolslikeBladeforfront-endandEloquentORMforback-end.2)Laravel'secosystem,includingLaravelMixandArtisan,enhancespro

Laravel的最新版本是什麼?Laravel的最新版本是什麼?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何簡化開發?最新的Laravel版本如何簡化開發?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)簡化的inimpliticmodelbinding,2)增強EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪裡可以找到最新的Laravel版本的發行說明?在哪裡可以找到最新的Laravel版本的發行說明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的發布說明。 1)發布說明提供了新功能、錯誤修復和改進的詳細信息。 2)它們包含示例和解釋,幫助理解新功能的應用。 3)注意新功能的潛在復雜性和向後兼容性問題。 4)定期審查發布說明可以保持更新並激發創新。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器