使用webonyx/graphql-php可快速搭建PHP的GraphQL API:先通过Composer安装库,定义User对象类型及包含user查询的Schema,编写resolve函数模拟数据返回,创建schema实例并在入口文件处理请求,最终返回JSON响应,支持前端调用。

PHP 中实现 GraphQL API 主要是通过 Webonyx/GraphQL-PHP 这个库,它是 PHP 社区中最成熟、最广泛使用的 GraphQL 实现。下面带你一步步搭建一个简单的 GraphQL API 服务。
composer require webonyx/graphql-php
例如,我们构建一个简单的“用户”查询 API:
创建 User 类型:
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
$userType = new ObjectType([
'name' => 'User',
'fields' => [
'id' => Type::nonNull(Type::int()),
'name' => Type::string(),
'email' => Type::string(),
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'user' => [
'type' => $userType,
'args' => [
'id' => Type::int()
],
'resolve' => function ($root, $args) {
// 模拟数据
$users = [
1 => ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com'],
2 => ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com'],
];
return $users[$args['id']] ?? null;
}
]
]
]);
use GraphQL\Type\Schema;
$schema = new Schema([
'query' => $queryType
]);
use GraphQL\GraphQL;
$input = json_decode(file_get_contents('php://input'), true);
$query = $input['query'];
$variableValues = $input['variables'] ?? null;
try {
$result = GraphQL::executeQuery($schema, $query, null, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json');
echo json_encode($output);
请求体示例:
立即学习“PHP免费学习笔记(深入)”;
{
"query": "{ user(id: 1) { id name email } }"
}
{
"data": {
"user": {
"id": 1,
"name": "Alice",
"email": "alice@example.com"
}
}
}
安装方法:composer require rebing/graphql-laravel
然后按文档发布配置并注册 schema。
以上就是PHPGraphQL怎么使用_PHP实现GraphQLAPI的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号