首頁  >  文章  >  php框架  >  Laravel使用管道處理名字, 實現統一處理

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

藏色散人
藏色散人轉載
2020-09-08 09:17:432185瀏覽
##上「使用中的管道」的資料中使用範例,並希望為需要的朋友提供幫助!

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

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

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

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

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


一、控制器

路由器部分

Route::get('/pipe', ['as'=>'pipe', 'uses'=>'PipeController@index']);
控製程式碼
input('name');
        // $name = Str::random(10);

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

二、管道部分

目錄結構如下:

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

interface

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

    下的程式碼如下:

     

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

  •   adeadc73d847caede3efd2c74f5a3826send($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,同時修改你的實作類別即可。

    三、結果說明

    造訪

    http://localhost/pipe?name=lisa之後,能成功列印出所獲得的結果。 User

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

    {
    "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.com。如有侵權,請聯絡admin@php.cn刪除