一、控制器
路由器部分
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'),
]);
});
你这样定义后,修改你的,同时修改你的实现类即可。
三、结果说明
访问之后,能成功打印出获取的结果。表内部,有数据保存成功。
看完本文有收获?点赞、分享是最大的支持!
领取专属 10元无门槛券
私享最新 技术干货