温馨提示×

PHP怎么使用GraphQL查询与获取数据

小亿
83
2024-05-06 17:05:56
栏目: 编程语言

使用PHP进行GraphQL查询与获取数据的步骤如下:

  1. 安装相关的PHP GraphQL库,推荐使用Webonyx GraphQL PHP库。可以通过Composer进行安装:
composer require webonyx/graphql-php
  1. 创建GraphQL查询的schema,定义数据类型和查询字段。
<?php

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;

$queryType = new ObjectType([
    'name' => 'Query',
    'fields' => [
        'hello' => [
            'type' => Type::string(),
            'resolve' => function () {
                return 'world';
            }
        ]
    ]
]);

$schema = new Schema([
    'query' => $queryType
]);

  1. 处理GraphQL查询请求,并执行查询。
<?php

use GraphQL\GraphQL;
use GraphQL\Type\Schema;

// 获取请求中的GraphQL查询字符串
$query = $_POST['query'];

try {
    $result = GraphQL::executeQuery($schema, $query)->toArray();
    echo json_encode($result);
} catch (Exception $e) {
    echo json_encode([
        'error' => [
            'message' => $e->getMessage()
        ]
    ]);
}
  1. 发送GraphQL查询请求,获取数据。
<?php

$query = '{
    hello
}';

$response = file_get_contents('http://localhost/graphql', false, stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => 'Content-Type: application/json',
        'content' => json_encode(['query' => $query])
    ]
]));

$data = json_decode($response, true);
print_r($data);

这样就可以使用PHP进行GraphQL查询与获取数据了。需要注意的是,GraphQL查询语句需要符合GraphQL的语法规范,可以通过GraphQL Playground等工具进行调试。

0