下面由laravel教程栏目带大家了解一下laravel中的管道,分享一个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下的代码如下:
<?phpnamespace AppPipesContracts;use Closure;interface PipeContracts{ public function handle($body, Closure $next);}
三个管道的类的代码LeftWords.php的代码
有道小P
有道小P,新一代AI全科学习助手,在学习中遇到任何问题都可以问我。
64 查看详情
<?phpnamespace AppPipes;use AppPipesContractsPipeContracts;use Closure;class LeftWords implements PipeContracts{ public function handle($body, Closure $next) { // TODO: Implement handle() method. $body = 'left-'.$body; return $next($body); }}
LeftWords.php的代码
<?phpnamespace AppPipes;use AppPipesContractsPipeContracts;use Closure;class RightWords implements PipeContracts{ public function handle($body, Closure $next) { // TODO: Implement handle() method. $body = $body.'-right'; return $next($body); }}
BothSidesWords.php的代码
<?phpnamespace AppPipes;use AppPipesContractsPipeContracts;use Closure;class BothSidesWords implements PipeContracts{ public function handle($body, Closure $next) { // TODO: Implement handle() method. $body = '['.$body.']'; 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,同时修改你的实现类即可。
三、结果说明
访问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中管道的使用方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/230878.html
微信扫一扫
支付宝扫一扫