下面由laravel教程栏目给大家分享一个laravel中的管道的使用实例,希望对需要的朋友有所帮助!
从代码的角度介绍管道的实际使用方式。有关管道的说明,网上已有较多的篇幅介绍,自行查阅。
本篇博客是使用管道处理名字, 实现统一处理的目的。
背景:
目前能找到的使用管道的介绍也很多,大多停留在对其介绍和引导,真正的深入到代码的部分不多。根据介绍,使用管道也有一定的阻碍,这里分享一篇关于使用管道的详细的代码实例,仅供参考。
本篇介绍是自己真实使用的过程的代码摘录,亲自测试,真实可用。只为抛砖引玉,不喜勿喷。
一、控制器路由器部分
route::get('/pipe', ['as'=>'pipe', 'uses'=>'pipecontroller@index']);
控制代码
<?phpnamespace 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('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下的代码如下:
<?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 = 'left-'.$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.'-right'; 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 = '['.$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中使用管道处理名字, 实现统一处理的详细内容。