前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在 Laravel 应用中构建 GraphQL API

在 Laravel 应用中构建 GraphQL API

作者头像
猿哥
发布2019-07-24 22:09:25
3.3K0
发布2019-07-24 22:09:25
举报
文章被收录于专栏:Web技术布道师Web技术布道师

代码示例:产品列表和用户列表的 API 例子

昨天我们学习了 在 Visual Code 中搭建 Laravel 环境,现在我们来学习 Facebook 的 GraphQL 。

GraphQL 是一种 API 查询语言,还是一种根据你为数据定义的类型系统执行查询的服务器端运行时。GraphQL 不依赖于任何指定的数据库或存储引擎,而是由你的代码和数据来作支持的。 graphql.org

GraphQL 可以提升 API 调用的灵活性,我们可以像写数据库查询语句一样来请求 API 来获取所需要的数据,这对构建复杂的 API 查询来说非常有用。GraphQL 还提供了可视化界面来帮助我们编写查询语句,还提供了自动补全的功能,这让编写查询更加简单。

https://github.com/graphql/graphiql

从以下图片可以看出,GraphQL 和 Rest 一样都是运行在业务逻辑层以外的:

开始

1. 安装 Laravel

使用下面命令安装最新版本的 Laravel :

代码语言:javascript
复制
# 在命令行中执行
composer global require "laravel/installer"
laravel new laravel-graphql
2. 添加 GraphQL 的包

使用 composer 安装 graphql-laravel,这个包提供了非常多的功能用于整合 Laravel 和 GraphQL 。

3. 创建模型

像下面这样创建模型和表 user_profiles, products, product_images,别忘了还要创建模型间的关系。

4. 创建查询和定义 GraphQL 的类型

GraphQL 中的查询与 Restful API 中的末端路径查询是一样的,查询只是用于获取数据,以及创建、更新、删除操作。我们把它称作 Mutation

GraphQL 中的 类型 用于定义查询中每个字段的类型定义,类型会帮助我们格式化查询结果中的有格式的字段,例如布尔类型,字符串类型,浮点类型,整数类型等等,以及我们的自定义类型。下面是查询和类型的目录结构:

这是 UsersQuery.phpUsersType.php 文件完整的源代码:

代码语言:javascript
复制
<?php
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;
class UsersQuery extends Query
{
   protected $attributes = [
       'name' => 'Users Query',
       'description' => 'A query of users'
   ];
   public function type()
   {        // 带分页效果的查询结果
       return GraphQL::paginate('users');
   }    // 过滤查询的参数
   public function args()
   {
       return [
           'id' => [
               'name' => 'id',
               'type' => Type::int()
           ],
           'email' => [
               'name' => 'email',
               'type' => Type::string()
           ]
       ];
   }
   public function resolve($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']);
           }
       };
       $user = User::with(array_keys($fields->getRelations()))
           ->where($where)
           ->select($fields->getSelect())
           ->paginate();
       return $user;
   }
}
代码语言:javascript
复制
<?php
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;
class UsersType extends GraphQLType
{
   protected $attributes = [
       'name' => 'Users',
       'description' => 'A type',
       'model' => User::class, // 定义用户类型的数据模型
   ];    // 定义字段的类型
   public function fields()
   {
       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'
           ],            // 数据模型 user_profiles 中的关联字段
           'user_profiles' => [
               'type' => GraphQL::type('user_profiles'),
               'description' => 'The profile of the user'
           ]
       ];
   }
   protected function resolveEmailField($root, $args)
   {
       return strtolower($root->email);
   }
}

在编写完查询语句和类型之后,我们需要编辑 config/graphql.php 文件,将查询语句和类型注册到 Schema 中。

代码语言:javascript
复制
<?php
use App\GraphQL\Query\ProductsQuery;
use App\GraphQL\Query\UsersQuery;
use App\GraphQL\Type\ProductImagesType;
use App\GraphQL\Type\ProductsType;
use App\GraphQL\Type\UserProfilesType;
use App\GraphQL\Type\UsersType;
return [
   'prefix' => 'graphql',
   'routes' => 'query/{graphql_schema?}',
   'controllers' => \Rebing\GraphQL\GraphQLController::class . '@query',
   'middleware' => [],
   'default_schema' => 'default',    // 注册查询命令 
   'schemas' => [
       'default' => [
           'query' => [
               'users' => UsersQuery::class,
               'products' => ProductsQuery::class,
           ],
           'mutation' => [
           ],
           'middleware' => []
       ],
   ],    // 注册类型
   'types' => [
       'product_images' => ProductImagesType::class,
       'products'  => ProductsType::class,
       'user_profiles'  => UserProfilesType::class,
       'users'  => UsersType::class,
   ],
   'error_formatter' => ['\Rebing\GraphQL\GraphQL', 'formatError'],
   'params_key'    => 'params'
];
5. Testing

我们可以使用 GraphiQL 来十分简单地编写查询语句,因为在编写的时候它可以自动补全,或者我们也可以使用 postman 来请求 API,下面是自动补全的示例:

下面是查询结果的示例

如果你想查阅源代码,可以访问以下地址

https://github.com/ardani/laravel-graphql

本文参与?腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-01-16,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 PHP技术大全 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 开始
    • 1. 安装 Laravel
      • 2. 添加 GraphQL 的包
        • 3. 创建模型
          • 4. 创建查询和定义 GraphQL 的类型
            • 5. Testing
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
            http://www.vxiaotou.com