在 Laravel 应用中构建 GraphQL API

栏目: PHP · 发布时间: 5年前

内容简介:代码示例:产品列表和用户列表的 API 例子昨天我们学习了

在  <a href='https://www.codercto.com/topics/5169.html'>Laravel</a>  应用中构建 GraphQL API

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

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

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

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

https://github.com/graphql/gr...

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

在 Laravel 应用中构建 GraphQL API

开始

1. 安装 Laravel

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

# 在命令行中执行
composer global require "laravel/installer"
laravel new laravel-graphql

2. 添加 GraphQL 的包

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

3. 创建模型

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

在 Laravel 应用中构建 GraphQL API

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

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

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

在 Laravel 应用中构建 GraphQL API

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

<?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;
    }
}
<?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 中。

<?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,下面是自动补全的示例:

在 Laravel 应用中构建 GraphQL API

下面是查询结果的示例

在 Laravel 应用中构建 GraphQL API

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

https://github.com/ardani/lar...

转自 PHP / Laravel 开发者社区 https://laravel-china.org/top...


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

智能时代

智能时代

吴军 / 中信出版集团 / 2016-8 / 68.00

大数据和机器智能的出现,对我们的技术发展、商业和社会都会产生重大的影响。作者吴军在《智能时代:大数据与智能革命重新定义未来》中指出,首先,我们在过去认为非常难以解决的问题,会因为大数据和机器智能的使用而迎刃而解,比如解决癌症个性化治疗的难题。同时,大数据和机器智能还会彻底改变未来的商业模式,很多传统的行业都将采用智能技术实现升级换代,同时改变原有的商业模式。大数据和机器智能对于未来社会的影响是全方......一起来看看 《智能时代》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器