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

21次阅读
没有评论

共计 1288 个字符,预计需要花费 4 分钟才能阅读完成。

使用 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 等工具进行调试。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-14发表,共计1288字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)