首页主机资讯Ubuntu PHP如何实现GraphQL查询

Ubuntu PHP如何实现GraphQL查询

时间2025-12-18 21:52:04发布访客分类主机资讯浏览1374
导读:在Ubuntu上使用PHP实现GraphQL查询,你需要遵循以下步骤: 安装必要的软件包 首先,确保你已经安装了PHP和Composer。然后,通过运行以下命令安装GraphQL PHP库: composer require webon...

在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和解析器,以满足你的应用程序需求。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: Ubuntu PHP如何实现GraphQL查询
本文地址: https://pptw.com/jishu/775540.html
Ubuntu PHP如何实现Websocket通信 Ubuntu PHP如何实现备份恢复

游客 回复需填写必要信息