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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值