首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Laravel中的管道的简单使用实例,可以学习参考

一、控制器

路由器部分

Route::get('/pipe',['as'=>'pipe','uses'=>'PipeController@index']);

控制代码

namespaceApp\Http\Controllers;

useApp\Pipes\LeftWords;

useApp\Pipes\RightWords;

useApp\Pipes\BothSidesWords;

useIlluminate\Http\Request;

useIlluminate\Pipeline\Pipeline;

useApp\User;

useIlluminate\Support\Str;

useIlluminate\Support\Facades\Hash;

classPipeControllerextendsController{

 /* 定义管道

  *

  * 第一步处理

  * 第二部处理

  * 第三部处理

  * */

 protected$pipes=[

     LeftWords::class,

     RightWords::class,

     BothSidesWords::class,

 ];

 // 首页

 publicfunctionindex(Request$request){

     $name=$request->input('name');

     // $name = Str::random(10);

     returnapp(Pipeline::class)

         ->send($name)

         ->through($this->pipes)

         ->then(function($content){

             returnUser::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

的代码

路径下的代码如下:

namespaceApp\Pipes\Contracts;

useClosure;

interfacePipeContracts{

 publicfunctionhandle($body,Closure$next);

}

三个管道的类的代码

的代码

namespaceApp\Pipes;

useApp\Pipes\Contracts\PipeContracts;

useClosure;

classLeftWordsimplementsPipeContracts{

 publicfunctionhandle($body,Closure$next) {

     // TODO: Implement handle() method.

     $body='left-'.$body;

     return$next($body);

 }

}

的代码

namespaceApp\Pipes;

useApp\Pipes\Contracts\PipeContracts;

useClosure;

classRightWordsimplementsPipeContracts{

 publicfunctionhandle($body,Closure$next){

     // TODO: Implement handle() method.

     $body=$body.'-right';

     return$next($body);

 }

}

的代码

namespaceApp\Pipes;

useApp\Pipes\Contracts\PipeContracts;

useClosure;

classBothSidesWordsimplementsPipeContracts{

 publicfunctionhandle($body,Closure$next){

     // TODO: Implement handle() method.

     $body='['.$body.']';

     return$next($body);

 }

}

这里我们使用管道默认的方法,你可以自定义方法名。像下面这样定义为处理方法名称。

returnapp(Pipeline::class)

       ->send($name)

       ->through($this->pipes)

       ->via('myHandleMethod')

       ->then(function($content){

           returnUser::create([

               'name'=>$content,

               'email'=>Str::random(10).'@gmail.com',

               'password'=>Hash::make('password'),

           ]);

       });

你这样定义后,修改你的,同时修改你的实现类即可。

三、结果说明

访问之后,能成功打印出获取的结果。表内部,有数据保存成功。

看完本文有收获?点赞、分享是最大的支持!

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20200919A022R700?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券