定制 sostariffe/php-graphql-client 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sostariffe/php-graphql-client

Composer 安装命令:

composer require sostariffe/php-graphql-client

包简介

GraphQL client and query builder.

README 文档

README

Build Status Codacy Badge Codacy Badge Total Downloads Latest Stable Version License

A GraphQL client written in PHP which provides very simple, yet powerful, query generator classes that make the process of interacting with a GraphQL server a very simple one.

Usage

There are 3 primary ways to use this package to generate your GraphQL queries:

  1. Query Class: Simple class that maps to GraphQL queries. It's designed to manipulate queries with ease and speed.
  2. QueryBuilder Class: Builder class that can be used to generate Query objects dynamically. It's design to be used in cases where a query is being build in a dynamic fashion.
  3. PHP GraphQL-OQM: An extension to this package. It Eliminates the need to write any GraphQL queries or refer to the API documentation or syntax. It generates query objects from the API schema, declaration exposed through GraphQL's introspection, which can then be simply interacted with.

Installation

Run the following command to install the package using composer:

composer require gmostafa/php-graphql-client

Object-to-Query-Mapper Extension

To avoid the hassle of having to write any queries and just interact with PHP objects generated from your API schema visit PHP GraphQL OQM repository at: https://github.com/mghoneimy/php-graphql-oqm

Query Examples

Simple Query

$gql = (new Query('companies'))
    ->setSelectionSet(
        [
            'name',
            'serialNumber'
        ]
    );

This simple query will retrieve all companies displaying their names and serial numbers.

Nested Queries

$gql = (new Query('companies'))
    ->setSelectionSet(
        [
            'name',
            'serialNumber',
            (new Query('branches'))
                ->setSelectionSet(
                    [
                        'address',
                        (new Query('contracts'))
                            ->setSelectionSet(['date'])
                    ]
                )
        ]
    );

This query is a more complex one, retrieving not just scalar fields, but object fields as well. This query returns all companies, displaying their names, serial numbers, and for each company, all its branches, displaying the branch address, and for each address, it retrieves all contracts bound to this address, displaying their dates.

Query With Arguments

$gql = (new Query('companies'))
    ->setArguments(['name' => 'Tech Co.', 'first' => 3])
    ->setSelectionSet(
        [
            'name',
            'serialNumber'
        ]
    );

This query does not retrieve all companies by adding arguments. This query will retrieve the first 3 companies with the name "Tech Co.", displaying their names and serial numbers.

Query With Array Argument

$gql = (new Query('companies'))
    ->setArguments(['serialNumbers' => [159, 260, 371]])
    ->setSelectionSet(
        [
            'name',
            'serialNumber'
        ]
    );

This query is a special case of the arguments query. In this example, the query will retrieve only the companies with serial number in one of 159, 260, and 371, displaying the name and serial number.

Query With Input Object Argument

$gql = (new Query('companies'))
    ->setArguments(['filter' => new RawObject('{name_starts_with: "Face"}')])
    ->setSelectionSet(
        [
            'name',
            'serialNumber'
        ]
    );

This query is another special case of the arguments query. In this example, we're setting a custom input object "filter" with some values to limit the companies being returned. We're setting the filter "name_starts_with" with value "Face". This query will retrieve only the companies whose names start with the phrase "Face".

The RawObject class being constructed is used for injecting the string into the query as it is. Whatever string is input into the RawObject constructor will be put in the query as it is without any custom formatting normally done by the query class.

The Query Builder

The QueryBuilder class can be used to construct Query objects dynamically, which can be useful in some cases. It works very similarly to the Query class, but the Query building is divided into steps.

That's how the "Query With Input Object Argument" example can be created using the QueryBuilder:

$builder = (new QueryBuilder('companies'))
    ->setArgument('filter', new RawObject('{name_starts_with: "Face"}'))
    ->selectField('name')
    ->selectField('serialNumber');
$gql = $builder->getQuery();

Constructing The Client

A Client object can easily be instantiated by providing the GraphQL endpoint URL. The Client constructor also receives an optional "authorizationHeaders" array, which can be used to add authorization headers to all requests being sent to the GraphQL server.

Example:

$client = new Client(
    'http://api.graphql.com',
    ['Authorization' => 'Basic xyz']
);

Running Queries

Running query with the GraphQL client and getting the results in object structure:

$results = $client->runQuery($gql);
$results->getData()->Company[0]->branches;

Or getting results in array structure:

$results = $client->runQuery($gql, true);
$results->getData()['Company'][1]['branches']['address']

Mutations

Mutations follow the same rules of queries in GraphQL, they select fields on returned objects, receive arguments, and can have sub-fields.

Here's a sample example on how to construct and run mutations:

$mutation = (new Mutation('createCompany'))
    ->setArguments(['companyObject' => new RawObject('{name: "Trial Company", employees: 200}')])
    ->setSelectionSet(
        [
            '_id',
            'name',
            'serialNumber',
        ]
    );
$results = $client->runQuery($mutation);

Mutations can be run by the client the same way queries are run.

Live API Example

GraphQL Pokemon is a very cool public GraphQL API available to retrieve Pokemon data. The API is available publicly on the web, we'll use it to demo the capabilities of this client.

Github Repo link: https://github.com/lucasbento/graphql-pokemon

API link: https://graphql-pokemon.now.sh/

This query retrieves Pikachu's evolutions and their attacks:

{
  pokemon(name: "Pikachu") {
    id
    number
    name
    evolutions {
      id
      number
      name
      weight {
        minimum
        maximum
      }
      attacks {
        fast {
          name
          type
          damage
        }
      }
    }
  }
}

That's how this query can be written using the query class and run using the client:

$client = new Client(
    'https://graphql-pokemon.now.sh/'
);
$gql = (new Query('pokemon'))
    ->setArguments(['name' => 'Pikachu'])
    ->setSelectionSet(
        [
            'id',
            'number',
            'name',
            (new Query('evolutions'))
                ->setSelectionSet(
                    [
                        'id',
                        'number',
                        'name',
                        (new Query('attacks'))
                            ->setSelectionSet(
                                [
                                    (new Query('fast'))
                                        ->setSelectionSet(
                                            [
                                                'name',
                                                'type',
                                                'damage',
                                            ]
                                        )
                                ]
                            )
                    ]
                )
        ]
    );
try {
    $results = $client->runQuery($gql, true);
}
catch (QueryError $exception) {
    print_r($exception->getErrorDetails());
    exit;
}
print_r($results->getData()['pokemon']);

Or alternatively, That's how this query can be generated using the QueryBuilder class:

$client = new Client(
    'https://graphql-pokemon.now.sh/'
);
$builder = (new QueryBuilder('pokemon'))
    ->setArgument('name', 'Pikachu')
    ->selectField('id')
    ->selectField('number')
    ->selectField('name')
    ->selectField(
        (new QueryBuilder('evolutions'))
            ->selectField('id')
            ->selectField('name')
            ->selectField('number')
            ->selectField(
                (new QueryBuilder('attacks'))
                    ->selectField(
                        (new QueryBuilder('fast'))
                            ->selectField('name')
                            ->selectField('type')
                            ->selectField('damage')
                    )
            )
    );
try {
    $results = $client->runQuery($builder, true);
}
catch (QueryError $exception) {
    print_r($exception->getErrorDetails());
    exit;
}
print_r($results->getData()['pokemon']);

Running Raw Queries

Although not the primary goal of this package, but it supports running raw string queries, just like any other client using the runRawQuery method in the Client class. Here's an example on how to use it:

$gql = <<<QUERY
query {
    pokemon(name: "Pikachu") {
        id
        number
        name
        attacks {
            special {
                name
                type
                damage
            }
        }
    }
}
QUERY;

$results = $client->runQuery($gql);

sostariffe/php-graphql-client 适用场景与选型建议

sostariffe/php-graphql-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.8k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2019 年 06 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「client」 「query」 「builder」 「query-builder」 「graphql」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 sostariffe/php-graphql-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 sostariffe/php-graphql-client 我们能提供哪些服务?
定制开发 / 二次开发

基于 sostariffe/php-graphql-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 5.8k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 102
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-06-25