如何使用Laravel中的管道

发布时间:2021-10-11 11:35:33 作者:iii
来源:亿速云 阅读:127

本篇内容主要讲解“如何使用Laravel中的管道”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用Laravel中的管道”吧!

一、控制器

路由器部分

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

控制代码

<?php

namespace 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

这里我们使用管道默认的方法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中的管道”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. [Linux管道和IPC]管道的高级应用--使用popen函数创建管道
  2. linux中的管道是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel

上一篇:怎么用PHP搭建一个班级网站

下一篇:php中能拦截SQL注入和xss的防火墙的安装使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》