cronqvist/graphql-client

执行查询和变异的 GraphQL 客户端

1.0.1 2020-10-09 10:05 UTC

README

一个简单的 PHP 库,用于与 GraphQL API 交互。

安装

运行以下命令使用 composer 安装此包

composer require cronqvist/graphql-client

使用方法

创建一个 Jc\GraphQL\GraphQLClient 的实例

$client = new GraphQLClient($url);
$client->setAuthToken('xxx');

// Define the query or queries
$query = <<<'QUERY'
    query GetUser($id: ID!) {
      user (id: $id) {
        id,
        name,
        email
      }
    }
QUERY;

// Fetch the result of the query or queries from the GraphQL endpoint
$response = $client->fetch($query, ['id' => 1]);

// Get all the data
$response->data();

// If you only send one query, you can get access to it directly:
$user = $response->firstData();

// You can also access the data directly (user) via the getter
$user = $response->user;


// Fetch can be used with three arguments where variables and headers are optional
$response = $client->fetch($query, $variables, $headers);

错误处理

// Easiest is to use the 'throwFirstError' method to throw an exception if any GraphQL error was returned:
$response->throwFirstError();

// or...

// Check if any errors exist
if($response->hasErrors()) {
    
    // Dump all errors
    var_dump($response->errors());
    
    // Or dump only the first error
    var_dump($response->firstError();
}