温馨提示×

Ubuntu PHP如何实现GraphQL查询

小樊
39
2025-12-18 11:54:14
栏目: 编程语言

在Ubuntu上使用PHP实现GraphQL查询,你需要遵循以下步骤:

  1. 安装必要的软件包

首先,确保你已经安装了PHP和Composer。然后,通过运行以下命令安装GraphQL PHP库:

composer require webonyx/graphql-php
  1. 创建GraphQL Schema

创建一个名为schema.graphqls的文件,用于定义GraphQL schema。这是一个简单的示例:

type Query {
    hello(name: String): String
}
  1. 创建解析器

创建一个名为resolvers.php的文件,用于定义GraphQL查询的解析器。这是一个简单的示例:

<?php

$helloResolver = function ($name) {
    return "Hello, " . $name . "!";
};

return [
    'Query' => [
        'hello' => $helloResolver,
    ],
];
  1. 创建GraphQL服务器

创建一个名为graphql_server.php的文件,用于设置GraphQL服务器。这是一个简单的示例:

<?php

require_once 'vendor/autoload.php';

use GraphQL\Executor\Executor;
use GraphQL\Type\Schema;
use GraphQL\HTTP\Request;
use GraphQL\HTTP\Response;

$schema = Schema::build()
    ->query(new GraphQL\Type\ObjectType([
        'name' => 'Query',
        'fields' => [
            'hello' => [
                'type' => GraphQL\Type\Type::string(),
                'args' => ['name' => GraphQL\Type\Type::string()],
                'resolve' => $GLOBALS['resolvers']['Query']['hello'],
            ],
        ],
    ]))
    ->build();

$executor = new Executor($schema);

$request = Request::create('/graphql', 'POST', ['query' => '{ hello(name: "World") }']);

$response = $executor->execute($request);
echo Response::fromResponse($response)->getContent();
  1. 运行GraphQL服务器

在终端中运行以下命令启动GraphQL服务器:

php graphql_server.php

现在,你可以使用任何GraphQL客户端(如Postman或GraphiQL)向http://localhost:8000/graphql发送查询。例如:

{
  hello(name: "World")
}

服务器将返回以下响应:

{
  "data": {
    "hello": "Hello, World!"
  }
}

这就是在Ubuntu上使用PHP实现GraphQL查询的基本步骤。你可以根据需要扩展schema和解析器,以满足你的应用程序需求。

0