laravel graphql php,结合 Laravel 初步学习 GraphQL

e8c8b6f7726a4edb5b250fa14679d429.png

本文字数:7134,大概需要14.27分钟。

aac66848ebb2e24e62f5cb54d3d085c4.png

按照官网所述的:

A query language for your API一种用于 API 的查询语言

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。 GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。

主要有以下几个特点:

请求你所要的数据不多不少。向你的 API 发出一个 GraphQL 请求就能准确获得你想要的数据,不多不少。 GraphQL 查询总是返回可预测的结果。

获取多个资源只用一个请求。GraphQL 查询不仅能够获得资源的属性,还能沿着资源间引用进一步查询。典型的 REST API 请求多个资源时得载入多个 URL,而 GraphQL 可以通过一次请求就获取你应用所需的所有数据。这样一来,即使是比较慢的移动网络连接下,使用 GraphQL 的应用也能表现得足够迅速。

描述所有的可能类型系统。GraphQL API 基于类型和字段的方式进行组织,而非入口端点。你可以通过一个单一入口端点得到你所有的数据能力。GraphQL 使用类型来保证应用只请求可能的数据,还提供了清晰的辅助性错误信息。应用可以使用类型,而避免编写手动解析代码。

API 演进无需划分版本。给你的 GraphQL API 添加字段和类型而无需影响现有查询。老旧的字段可以废弃,从工具中隐藏。通过使用单一演进版本,GraphQL API 使得应用始终能够使用新的特性,并鼓励使用更加简洁、更好维护的服务端代码。

使用你现有的数据和代码。GraphQL 让你的整个应用共享一套 API,而不用被限制于特定存储引擎。GraphQL 引擎已经有多种语言实现,通过 GraphQL API 能够更好利用你的现有数据和代码。你只需要为类型系统的字段编写函数,GraphQL 就能通过优化并发的方式来调用它们。

Demo

先写一个 Demo 来看看如何结合 Laravel 使用 GraphQL。

引入 rebing/graphql-laravel

composer require "rebing/graphql-laravel"

因为 Laravel 5.5 开始,有「包自动发现」http://mp.weixin.qq.com/s/AD05BiKjPsI2ehC-mhQJQw功能,所以 Laravel 5.5 可以不用手动引入该 provider 和 aliase。之前的版本需要引入对应的 provider 和 aliase。

"extra": {    "laravel": {        "providers": [            "Rebing\\GraphQL\\GraphQLServiceProvider"        ],        "aliases": {            "GraphQL": "Rebing\\GraphQL\\Support\\Facades\\GraphQL"        }    }}

创建 Type 和 Query

Type: 通过 Type,可以帮助我们格式化查询结果的类型,主要有 boolean、string、float、int 等,同时也可以自定义类型

Query: 通过 Query,可以获取我们需要的数据。

在项目根目录创建 GraphQL 文件件用于存放 Type 和 Query

671f0e51046b15753b4d66169d1b84c6.png

定义 UsersType:

<?php /** * User: yemeishu */namespace App\GraphQL\Type;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Type as GraphQLType;classUsersTypeextendsGraphQLType{    protected $attributes = [        'name' => 'Users',        'description' => 'A type',        'model' => User::class, // define model for users type    ];    // define field of type    public functionfields(){        return [            'id' => [                'type' => Type::nonNull(Type::int()),                'description' => 'The id of the user'            ],            'email' => [                'type' => Type::string(),                'description' => 'The email of user'            ],            'name' => [                'type' => Type::string(),                'description' => 'The name of the user'            ]        ];    }    protected functionresolveEmailField($root, $args){        return strtolower($root->email);    }}

定义 Query:

<?php /** * User: yemeishu */namespace App\GraphQL\Query;use App\User;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Query;use Rebing\GraphQL\Support\SelectFields;classUsersQueryextendsQuery{    protected $attributes = [        'name' => 'users',        'description' => 'A query of users'    ];    public functiontype(){        return Type::listOf(GraphQL::type('users'));    }    // arguments to filter query    public functionargs(){        return [            'id' => [                'name' => 'id',                'type' => Type::int()            ],            'email' => [                'name' => 'email',                'type' => Type::string()            ]        ];    }    public functionresolve($root, $args, SelectFields $fields){        $where = function($query)use($args){            if (isset($args['id'])) {                $query->where('id',$args['id']);            }            if (isset($args['email'])) {                $query->where('email',$args['email']);            }        };        $users = User::with(array_keys($fields->getRelations()))            ->where($where)            ->select($fields->getSelect())            ->get();        return $users;    }}

配置 graphql.php

将写好的 UsersType 和 UsersQuery 注册到 GraphGL 配置文件中。

3b2b694d42350545351ede48286b58b0.png

测试

我们主要有两种途径用于测试,第一种就是向测试 RESTful 接口一样,使用 Postman:

5ce1405021326c7af7d8766b90faf266.png

另一种方式就是利用 GraphiQL:

An in-browser IDE for exploring GraphQL.https://github.com/graphql/graphiql

这里我们使用noh4ck/graphiql

// 1. 安装插件composer require "noh4ck/graphiql:@dev"// 2. 加入 providerGraphiql\GraphiqlServiceProvider::class// 3. 命令artisan graphiql:publish

配置文件可看出 route 为:/graphql-ui

701b251c461e35ff04e5a4a578f73d9b.png

运行结果:

32630840a8c8c1240fdfea50e5ab78d5.png

还可以通过传入参数 (id: 1) 来筛选数据:

32efa426663102b8641748ddfd8490c5.png

Mutation

通过 Demo,我们初步了解 GraphQL 的 Query 查询方法,接下来我们看看 Mutation 的用法。

如果说 Query 是 RESTful 的「查」,那么 Mutation 充当的作用就是「增、删、改」了。

cf7e10ccb57a1c0cafdd457b7a96d8cf.png

在 GraphQL 文件夹下创建「Mutation」文件夹,存放和 Mutation 相关的类。

Create Mutation Class

<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classNewUserMutationextendsMutation{    protected $attributes = [        'name' => 'NewUser'    ];    public functiontype(){        return GraphQL::type('users');    }    public functionargs(){        return [            'name' => [                'name' => 'name',                'type' => Type::nonNull(Type::string())            ],            'email' => [                'name' => 'email',                'type' => Type::nonNull(Type::string())            ],            'password' => [                'name' => 'password',                'type' => Type::nonNull(Type::string())            ]        ];    }    public functionresolve($root, $args){        $args['password'] = bcrypt($args['password']);        $user = User::create($args);        if (!$user) {            return null;        }        return $user;    }}

Update Mutation Class

<?php /** * User: yemeishu * Date: 2018/4/3 */namespace App\GraphQL\Mutation;use GraphQL\Type\Definition\Type;use Rebing\GraphQL\Support\Facades\GraphQL;use Rebing\GraphQL\Support\Mutation;use App\User;classUpdateUserMutationextendsMutation{    protected $attributes = [        'name' => 'UpdateUser'    ];    public functiontype(){        return GraphQL::type('users');    }    public functionargs(){        return [            'id' => [                'name' => 'id',                'type' => Type::nonNull(Type::int())            ],            'name' => [                'name' => 'name',                'type' => Type::nonNull(Type::string())            ]        ];    }    public functionresolve($root, $args){        $user = User::find($args['id']);        if (!$user) {            return null;        }        $user->name = $args['name'];        $user->save();        return $user;    }}

配置 graphql.php

把 NewUserMutation 和 UpdateUserMutation 加入 graphql mutation 配置中

0e10bb45713b83fa63c7bcf392dc9ac8.png

测试

421130b56969f81ef1c6fe8c7afefc0a.png

如上图,创建两个 mutation,可以选择任意一个看运行效果。

创建一个 User:

893147d10f87f3257f7c2457217cd5bf.png

更新「id: 1」用户信息:

65696c1476f058766be876b04697dd78.png

其中在 graphql-ui 界面,右上角还可以看到「Docs」,点开可以查看这两个 mutiation 的说明:

5cec3dca4cfa3ed3f1a79155f5c0208d.png

总结

通过简单的「增改查」User 来初步了解 GraphQL 的 Query 和 Mutation 的使用,接下来可以将 GraphQL 作为微服务的「网关」层的前一层来使用。

「未完待续」

coding01 期待您继续关注

2a9d61e8a9a5d60c64d4b78e4faec4a4.gif

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/279041.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

wi-fi共享大师免广告_如何保护Wi-Fi网络免受入侵

wi-fi共享大师免广告Insecure Wi-Fi is the easiest way for people to access your home network, leech your internet, and cause you serious headaches with more malicious behavior. Read on as we show you how to secure your home Wi-Fi network. 不安全的Wi-Fi是人们…

MongoDb分片集群认证

本文主要基于已经搭建好的未认证集群&#xff0c;结合上篇Mongodb副本集分片集群模式环境部署&#xff08;https://www.cnblogs.com/woxingwoxue/p/9875878.html&#xff09;&#xff0c; MongoDb分片集群认证几个主要流程1.在分片集群环境中&#xff0c;副本集内成员之间需要用…

汉克尔变换matlab,HankelTransform

HankelTransform所属分类&#xff1a;matlab例程开发工具&#xff1a;matlab文件大小&#xff1a;135KB下载次数&#xff1a;66上传日期&#xff1a;2011-09-17 13:41:39上 传 者&#xff1a;甜头说明&#xff1a; Matlab Hankel变换源代码&#xff0c;可以直接当做MATLAB too…

【材质】色彩基础

RBG颜色空间 目前&#xff0c;绝大部分显示器采用的是RGB颜色标准&#xff0c;因此几乎所有软件也采用此标准&#xff0c;UE4也不例外。 R、G、B这三个字母分别代表红色&#xff08;red&#xff09;、绿色&#xff08;green&#xff09;、蓝色&#xff08;blue&#xff09;三条…

使用mintty(_如何使用Mintty改善Cygwin控制台

使用mintty(Cygwin’s great for getting some Linux command-line goodness in Windows, but using the Windows Shell to access it kills some of that magic. Using Mintty and a few other methods, you can make the experience much more luxurious. Cygwin非常适合在Wi…

18.phpmyadmin 4.8.1 远程文件包含漏洞(CVE-2018-12613)

phpmyadmin 4.8.1 远程文件包含漏洞&#xff08;CVE-2018-12613&#xff09; phpMyAdmin是一套开源的、基于Web的MySQL数据库管理工具。其index.php中存在一处文件包含逻辑&#xff0c; 通过二次编码即可绕过检查&#xff0c;造成远程文件包含漏洞。 受影响版本: phpMyAdmin 4.…

开源php面板,宝塔面板nginx安装终于搞定了

server{listen 80;server_name lvyou.yssknet.com;index index.php index.html index.htm default.php default.htm default.html;root ***********/public;#SSL-START SSL相关配置&#xff0c;请勿删除或修改下一行带注释的404规则#error_page 404/404.html;#SSL-END#ERROR-PA…

[Erlang 0004] Centos 源代码编译 安装 Erlang

由于最终部署的生产环境是Centos&#xff0c;所以我需要在Centos中安装Erlang B13R04 &#xff0c;第一次做这件事情破费周折&#xff0c;主要是对Erlang依赖的库不熟悉&#xff0c;总是编译不过&#xff1b;这里梳理一下安装过程中的细节&#xff1a; Erlang依赖哪些库&#x…

关于“Python”的核心知识点整理大全38

14.1.1 创建 Button 类 由于Pygame没有内置创建按钮的方法&#xff0c;我们创建一个Button类&#xff0c;用于创建带标签的实心矩形。 你可以在游戏中使用这些代码来创建任何按钮。下面是Button类的第一部分&#xff0c;请将这个类保存为 文件button.py&#xff1a; button.py …

同步您的Google Chrome书签,主题等

Do you regularly use Google Chrome on multiple computers? Here’s how you can keep almost everything in your browser synced easily in Google Chrome. 您是否经常在多台计算机上使用Google Chrome&#xff1f; 您可以通过以下方法在Google Chrome浏览器中轻松同步浏…

Python中函数的参数传递与可变长参数

转自旭东的博客原文 Python中函数的参数传递与可变长参数 Python中传递参数有以下几种类型&#xff1a; &#xff08;1&#xff09;像C一样的默认缺省函数 &#xff08;2&#xff09;根据参数名传参数 &#xff08;3&#xff09;可变长度参数 示例如下&#xff1a; &#xff08…

matlab的plot没有反应,用plot画图没有反应

本帖最后由 躺着看雨 于 2018-6-7 10:35 编辑0.0854232732222489 -1.47227270375083e-08 17.0844721322814 17.08465464444980.0854232767446789 -1.41282430199396e-08 17.0844728367686 17.08465534893580.0854232802671089 …

转]MATLAB 与 C 语言的接口

MATLAB 到 C 语言程序的转换可以由两种途径完成&#xff0c;其一是 MATLAB 自己提供的 C 语言翻译程序 mcc, 另一种是原第 3 方公司 MathTools 开发的 MATCOM。后者出现较早&#xff0c;功能远比 MATLAB 自己的翻译程序强大&#xff0c;所以 MathTools 公司已经被 MathWorks 公…

找call写call_如何将Google Call Widget添加到任何网页

找call写callAdding a Google Call Widget to your website or blog allows visitors to contact you using your Google Voice number. The widget provides an easy and cost-effective way to provide live customer support without the customer knowing your real number…

XML与web开发-01- 在页面显示和 XML DOM 解析

前言&#xff1a; 关于 xml 特点和基础知识&#xff0c;可以菜鸟教程进行学习&#xff1a;http://www.runoob.com/xml/xml-tutorial.html 本系列笔记&#xff0c;主要介绍 xml 在 web 开发时需要了解的知识 XML 在页面显示数据 XML 指可扩展标记语言&#xff08;eXtensible Mar…

酷安应用市场php源码,酷安应用市场 v11.0.3-999 去广告极限精简版

酷安&#xff0c;真实有趣的数码社区。酷安app&#xff0c;国内安卓应用市场客户端&#xff0c;应用资源丰富&#xff0c;应用开发者水准高&#xff0c;应用无首发Logo&#xff0c;原汁原味上架&#xff0c;得到了安卓用户群广泛认可。有人说现在的酷安市场(酷安网)没有以前那么…

再战android-语音识别2(修改配置)

可怕的半桶水一直在晃。程序中需要根据用户的选择设置语音识别的语言&#xff08;目前科大讯飞支持英文、普通话、粤语&#xff09;&#xff0c;不想每次要用户去IatSetting中去改&#xff0c;需要能直接修改IatSetting的设置。之前移植的IatSetting页面没有细究&#xff0c;直…

chromebook刷机_如何将网站添加到您的Chromebook架子上

chromebook刷机Bookmarks are great to keep your favorite sites nearby, but they aren’t the fastest option out there. Instead, why not add shortcuts for your favorite websites right on the Chromebook shelf? 书签可以很好地将您喜欢的网站保留在附近&#xff0c…

php判断外链,php检查字符串中是否有外链的方法

这篇文章主要介绍了php检查字符串中是否有外链的方法,涉及php针对字符串的正则匹配的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下本文实例讲述了php检查字符串中是否有外链的方法。分享给大家供大家参考。具体实现方法如下&#xff1a;/*** is_external_link 检测字符…

【经验分享】产品、运营人如何告别重复的数据分析工作?

我是一名互联网的运营打杂MM&#xff0c;除了每天繁忙的工作&#xff0c;每周、每月的数据汇报也是我头疼的东东。因为本身我不聪明&#xff0c;数学也不是太好&#xff0c;对数据不那么爱&#xff0c;而且还要做数据分析&#xff0c;对于我这种数据小白分分钟崩溃。每周、每月…