在Ubuntu上使用PHP实现GraphQL查询,你需要遵循以下步骤:
首先,确保你已经安装了PHP和Composer。然后,通过运行以下命令安装GraphQL PHP库:
composer require webonyx/graphql-php
创建一个名为schema.graphqls的文件,用于定义GraphQL schema。这是一个简单的示例:
type Query {
hello(name: String): String
}
创建一个名为resolvers.php的文件,用于定义GraphQL查询的解析器。这是一个简单的示例:
<?php
$helloResolver = function ($name) {
return "Hello, " . $name . "!";
};
return [
'Query' => [
'hello' => $helloResolver,
],
];
创建一个名为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();
在终端中运行以下命令启动GraphQL服务器:
php graphql_server.php
现在,你可以使用任何GraphQL客户端(如Postman或GraphiQL)向http://localhost:8000/graphql发送查询。例如:
{
hello(name: "World")
}
服务器将返回以下响应:
{
"data": {
"hello": "Hello, World!"
}
}
这就是在Ubuntu上使用PHP实现GraphQL查询的基本步骤。你可以根据需要扩展schema和解析器,以满足你的应用程序需求。