> 백엔드 개발 > PHP 튜토리얼 > PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

青灯夜游
풀어 주다: 2023-04-09 22:52:01
앞으로
4308명이 탐색했습니다.

이 글에서는 GraphQL에 대해 소개하고, PHP에서 GraphQL을 설치하고 사용하는 방법을 자세히 소개합니다. 도움이 필요한 친구들이 모두 참고할 수 있기를 바랍니다.

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

GraphQL 소개

GraphQL은 최신 HTTP API 인터페이스 구성 방법이며, 클라이언트는 요청 시 필요한 데이터를 쿼리할 수 있습니다.
GraphQL은 API 호출의 유연성을 향상시켜 데이터베이스 쿼리문을 작성하는 것처럼 필요한 데이터를 얻기 위해 API를 요청할 수 있으며 이는 복잡한 API 쿼리를 작성하는 데 매우 유용합니다. 按需查询需要的数据。
GraphQL 可以提升 API 调用的灵活性,我们可以像写数据库查询语句一样来请求 API 来获取所需要的数据,这对构建复杂的 API 查询来说非常有用。

与REST对比

REST的核心思想就是资源,每个资源都能用一个URL来表示,你能通过一个GET请求访问该URL从而获取该资源。根据当今大多数API的定义,你很有可能会得到一份JSON格式的数据响应,整个过程大概是这样:

GET /user/1
{
    "username":"姓名",
    "age":20,
    "sex":"男"
}
로그인 후 복사
GET /book/1
{
    "book":"书名",
    "author":"作者",
    "country":"中国"
}
로그인 후 복사

从上面的示例可以看出,如果前端需要user/1book/1的时候需要调用2次接口,并且如果前端只需要user/1里面的username,而上面的接口获取了username以外的数据,那么对于前端而言,除 username 之外的数据无处可用,造成了资源的浪费。

如果我们使用GraphQL来进行查询的话,与REST方式相比,只需要调用一次并且可以查询我们指定的字段,避免了资源的浪费,并且更加高效。

query {
 user(id:1) {
     username
 }
 book(id:1){
     book,
     author,
     country
 }
}
로그인 후 복사

推荐学习:《PHP视频教程

安装graphql-php包

composer require webonyx/graphql-php
로그인 후 복사

开始

1、安装完成之后,我们先编写一个简单示例,来看看graphql-php怎么用,具体代码如下:这段代码中,我们定义了一个名为phoneNumber的字段,然后通过postman来调用我们编写的代码。

<?php
require_once __DIR__ . &#39;/vendor/autoload.php&#39;;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;

$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;phoneNumber&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;resolve&#39; => function () {
                return 1875555555;
            }
        ]
    ],
]);

$schema = new Schema([
    &#39;query&#39; => $queryType,
]);



$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);

$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {

    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사

2、使用postman来调用我们刚刚编写的代码,以下是我们查询结果的示例

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

介绍

从上面的示例中,我们可以看到示例主要引入了4个类

use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
로그인 후 복사

Schema 类

Schema 是类型层次结构的容器,它接受构造函数中的根类型并向内部 GrahpQL 工具提供接收你的类型信息的方法。

配置选项

包含以下选项的数组:

REST와의 비교
GraphQL\Type\Definition\ObjectType
로그인 후 복사
로그인 후 복사
<?php
use GraphQL\Type\Definition\Type;
// 内置标量类型
Type::string();  // String 类型
Type::int();     // Int 类型
Type::float();   // Float 类型
Type::boolean(); // Boolean 类型
Type::id();      // ID 类型
로그인 후 복사
로그인 후 복사
위 예에서 볼 수 있듯이 프런트 엔드에 사용자가 필요한 경우 /1</ code> 및 <code>book/12회 인터페이스를 호출해야 하며 프런트 엔드에 user의 <code>username<만 필요한 경우 /1 /code>, 그리고 위의 인터페이스는 사용자 이름 이외의 데이터를 얻습니다. 그런 다음 프런트 엔드의 경우 사용자 이름 이외의 데이터를 사용할 수 없습니다. 자원 낭비.
OptionTypeNotes
queryObjectType必须。 读取 API 中包含根级字段的对象类型 (通常命名为 "Query"),用于读取数据
mutationObjectType写入 API 中包含根级字段的对象类型 (通常命名为 "Mutation"),数据变更时会用到
subscriptionObjectType保留用于将来的描述实现。目前表现为 graphql-js 自检查询的兼容,用于各种客户端 (如 Relay 或 GraphiQL)
directivesDirective[]默认包含内建指令 @skip@include

如果你传递自定义指令并且依然想使用内建指令,请声明添加它们。例如:

array_merge(GraphQL::getStandardDirectives(), [$myCustomDirective]);
typesObjectType[]对象类型类表,它在静态 schema 解析期间是不能被 graphql-php 发现的。

大多数情况下,对象类型未曾在字段中被直接引用,但它依然是 schema 的一部分时会用到,因为它实现了一个在 resolveType 中调用解析为此对象类型的接口。

请注意,您在此处无需传递所有类型 ,它只是具体用例的解决方法。
typeLoadercallable

REST의 핵심 아이디어는 리소스입니다. 각 리소스는 URL로 표시되어 얻을 수 있습니다. 자원. 오늘날 대부분의 API 정의에 따르면 JSON 형식의 데이터 응답을 얻을 가능성이 높습니다. 전체 프로세스는 대략 다음과 같습니다.
GraphQL을 사용하여 쿼리하면 REST 메서드에 비해 🎜한 번만🎜 호출하면 되며 🎜지정🎜한 필드를 쿼리할 수 있어 리소스 낭비를 피하고 더 효율적입니다. 🎜
$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;phoneNumber&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;resolve&#39; => function () {
                return 1875555555;
            }
        ]
    ],
]);
로그인 후 복사
로그인 후 복사
🎜추천 학습: "PHP 비디오 튜토리얼"🎜< h2 data-id="heading-2">🎜graphql-php 패키지 설치🎜🎜
use GraphQL\GraphQL;

$result = GraphQL::executeQuery(
    $schema, 
    $queryString, 
    $rootValue = null, 
    $context = null, 
    $variableValues = null, 
    $operationName = null,
    $fieldResolver = null,
    $validationRules = null
);
로그인 후 복사
로그인 후 복사

🎜Start🎜🎜🎜1. 설치가 완료되면 먼저 다음을 작성합니다. 간단한 예로 graphql-php 사용법을 살펴보겠습니다. 구체적인 코드는 다음과 같습니다. 이 코드에서는 phoneNumber라는 필드를 정의한 후 postman을 통해 작성한 코드를 호출합니다. 🎜
<?php

require_once __DIR__ . &#39;/vendor/autoload.php&#39;;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;phoneNumber&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;resolve&#39; => function () {
                return 1875555555;
            }
        ],

        &#39;echo&#39; => [
            &#39;type&#39; => Type::string(),
            &#39;args&#39; => [
                &#39;message&#39; => Type::string(),
            ],
            &#39;resolve&#39; => function ($root, $args) {
                return &#39;echo msg result:&#39; . ($args[&#39;message&#39;] ?? &#39;nothing&#39;);
            }
        ],
    ],
]);

$schema = new Schema([
    &#39;query&#39; => $queryType
]);


$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);

$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {

    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사
로그인 후 복사
🎜2. postman을 사용하여 방금 작성한 코드를 호출합니다. 다음은 쿼리 결과의 예입니다🎜🎜PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명🎜

🎜Introduction🎜🎜🎜위의 예를 보면, 주로 4가지 클래스를 소개합니다. 🎜
<?php
require_once __DIR__ . &#39;/vendor/autoload.php&#39;;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

$userType = new ObjectType([
    &#39;name&#39; => &#39;userType&#39;,
    &#39;description&#39; => &#39;用户详情&#39;,
    &#39;fields&#39; => [
        &#39;uid&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;description&#39; => &#39;用户ID&#39;
        ],
        &#39;name&#39; => Type::string()
    ]
]);


$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;oneUser&#39; => [
            &#39;type&#39; => $userType, // 我们这里指定type为我们上面创建的$userType
            &#39;description&#39; => &#39;用户列表&#39;,
            &#39;args&#39; => [
                &#39;uid&#39; => [
                    &#39;type&#39; => Type::int(),
                    &#39;defaultValue&#39; => 222
                ]
            ],
            &#39;resolve&#39; => function($root, $args) {
                return  [
                    "uid" => $args[&#39;user_id&#39;] ?? 3,
                    "name" => "xzl",
                ];
            }
        ],
    ]
]);

$schema = new Schema([
    &#39;query&#39; => $queryType
]);

$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);
$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {
    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사
로그인 후 복사

🎜스키마 클래스 🎜

🎜스키마는 유형 계층의 컨테이너이며 생성자에서 루트 유형을 받아들이고 내부 클래스에 수신을 제공합니다. 유형 정보에 대한 GrahpQL 도구 방법. 🎜

🎜구성 옵션🎜

🎜다음 옵션을 포함하는 배열: 🎜🎜🎜query🎜🎜ObjectType🎜🎜🎜필수입니다. 🎜 읽기 API(일반적으로 "Query"라고 함)의 루트 수준 필드가 포함된 개체 유형은 데이터를 읽는 데 사용됩니다. 🎜🎜🎜mutation🎜🎜ObjectType🎜🎜쓰기 API에 포함됨 데이터가 변경될 때 사용되는 루트 수준 필드(일반적으로 "Mutation"이라고 함)의 객체 유형 🎜🎜🎜subscription🎜🎜ObjectType🎜🎜은 향후 설명 구현을 위해 예약되어 있습니다. 현재 다양한 클라이언트(예: Relay 또는 GraphiQL)에서 사용되는 🎜graphql-js🎜 자체 검사 쿼리와 호환됩니다. 🎜🎜🎜directives🎜🎜Directive[]🎜🎜기본적으로 포함되어 있습니다. 빌드 지시어 🎜@skip🎜 및 🎜@include🎜.

사용자 정의 지시문을 전달하고 여전히 내장된 지시문을 사용하려면 이를 명시적으로 추가하세요. 예:

array_merge(GraphQL::getStandardDirectives(), [$myCustomDirective]);🎜🎜🎜types🎜🎜ObjectType[]</ code >🎜🎜객체 유형 클래스 테이블. 정적 스키마 구문 분석 중에 🎜graphql-php🎜에서 검색할 수 없습니다. <br/><br/>대부분의 경우 객체 유형은 필드에서 직접 참조되지 않지만 🎜resolveType🎜 유형의 인터페이스에서 이 객체를 해결하기 위한 호출을 구현하기 때문에 여전히 스키마의 일부입니다. <br/><br/> 여기에서 모든 유형을 전달할 필요는 없으며 특정 사용 사례에 대한 해결 방법일 뿐입니다. 🎜🎜<tr>🎜typeLoader🎜🎜<code>호출 가능🎜🎜🎜function($name)🎜 지정된 유형 인스턴스 이름을 반환합니다. 여러 호출의 경우 동일한 인스턴스가 반환되어야 합니다. 아래의 지연 유형 로딩 섹션을 참조하세요. 🎜🎜🎜🎜

ObjectType类

GraphQL\Type\Definition\ObjectType
로그인 후 복사
로그인 후 복사

对象类型是典型的 GraphQL 应用程序中使用最频繁的基元。

配置选项

옵션유형메모
OptionTypeNotes
namestring必须。 Schema 中此对象的唯一名称
fieldsarray or callable必须。 描述对象字段或可调用返回此类数组的数组。
descriptionstring呈现于客户端的参数文本说明(例如:用于 GraphiQL 自动生成文档 )
interfacesarray or callable此类型实现的接口列表或返回此类列表的可调用接口。

内置标量类型

<?php
use GraphQL\Type\Definition\Type;
// 内置标量类型
Type::string();  // String 类型
Type::int();     // Int 类型
Type::float();   // Float 类型
Type::boolean(); // Boolean 类型
Type::id();      // ID 类型
로그인 후 복사
로그인 후 복사

字段参数

GraphQL 对象类型上的所有字段都有 0 个或多个参数,使用在 args 的字段定义上。每个参数数组参考以下说明:

OptionTypeNotes
namestring必须。 参数名称。 为空时,使用 args 数组键值
typeType必须。
descriptionstring呈现于客户端的参数文本说明
defaultValuescalar当前参数默认值

示例

$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;phoneNumber&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;resolve&#39; => function () {
                return 1875555555;
            }
        ]
    ],
]);
로그인 후 복사
로그인 후 복사

GraphQL 类

GraphQL类主要在查询的时候用到,我们可以用 GraphQL::executeQuery 方法来执行查询

executeQuery 方法的参数说明

参数类型说明
schemaGraphQL\Type\Schema必须。 Schema应用实例
queryStringstring or GraphQL\Language\AST\DocumentNode必须。 解析,验证并执行现有的 GraphQL 查询字符。 如果在执行之前解析其他查询,则在此处传递相应的 AST 文档节点来避免新的解析。
rootValuemixed表示数据图结构的基础值。作为Query type 字段解析传递的第一个参数。如果现有该值已被 Query type 解析过,则可忽略或设置为 null 值。
contextmixed字段解析器的共享信息。 常用来传递已登录用户信息,位置详情等。

它将用在所有字段解析器的第 3 个参数。
variableValuesarray变量的映射,该值将随同查询字符串一起传递。请查阅 GraphQL官网查询变量的相关
operationNamestring指定请求方可执行的操作, 防止条件查询字符包含多级操作。
fieldResolvercallableSchema 参数 schema 中未实现的解析器函数。
validationRulesarray查询验证规则组,默认所有规则。空数组将跳过查询验证 (对于持久化查询将会比较方便,查询会在持久化之前默认已验证,并在执行期间假设符合规则)。
use GraphQL\GraphQL;

$result = GraphQL::executeQuery(
    $schema, 
    $queryString, 
    $rootValue = null, 
    $context = null, 
    $variableValues = null, 
    $operationName = null,
    $fieldResolver = null,
    $validationRules = null
);
로그인 후 복사
로그인 후 복사

简单示例

我们介绍完GraphQL几个概念之后,用几个简单的示例带大家来体验一下。

普通示例

在这个示例中我们定义了2个字段,分别是phoneNumberecho,其中phoneNumber为 Type::int()类型,echoType::string()类型,同时echo字段带有一个参数为message

<?php

require_once __DIR__ . &#39;/vendor/autoload.php&#39;;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;phoneNumber&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;resolve&#39; => function () {
                return 1875555555;
            }
        ],

        &#39;echo&#39; => [
            &#39;type&#39; => Type::string(),
            &#39;args&#39; => [
                &#39;message&#39; => Type::string(),
            ],
            &#39;resolve&#39; => function ($root, $args) {
                return &#39;echo msg result:&#39; . ($args[&#39;message&#39;] ?? &#39;nothing&#39;);
            }
        ],
    ],
]);

$schema = new Schema([
    &#39;query&#39; => $queryType
]);


$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);

$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {

    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사
로그인 후 복사

执行示例代码结果

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

我们可以看到,在请求时我们传了phoneNumberecho两个字段,并且messagetest

对象示例

我们在上面说过,对象类型是典型的 GraphQL 应用程序中使用最频繁的基元,一个对象类型里面可以包含宁外一个对象类型,我们可以新定义一个名为$userTypeObjectType,然后在oneUser指定它的类型为$userType,这样我们执行查询的时候,oneUser就会返回一个对象。

<?php
require_once __DIR__ . &#39;/vendor/autoload.php&#39;;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

$userType = new ObjectType([
    &#39;name&#39; => &#39;userType&#39;,
    &#39;description&#39; => &#39;用户详情&#39;,
    &#39;fields&#39; => [
        &#39;uid&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;description&#39; => &#39;用户ID&#39;
        ],
        &#39;name&#39; => Type::string()
    ]
]);


$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;oneUser&#39; => [
            &#39;type&#39; => $userType, // 我们这里指定type为我们上面创建的$userType
            &#39;description&#39; => &#39;用户列表&#39;,
            &#39;args&#39; => [
                &#39;uid&#39; => [
                    &#39;type&#39; => Type::int(),
                    &#39;defaultValue&#39; => 222
                ]
            ],
            &#39;resolve&#39; => function($root, $args) {
                return  [
                    "uid" => $args[&#39;user_id&#39;] ?? 3,
                    "name" => "xzl",
                ];
            }
        ],
    ]
]);

$schema = new Schema([
    &#39;query&#39; => $queryType
]);

$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);
$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {
    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사
로그인 후 복사

执行示例代码结果

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

列表示例

在平时的开发请求中,我们从后端接口获取数据的时候,大部分都是以列表的形式返回的,我们可以通过Type::listOf方法来指定我们返回的字段是一个列表。

<?php
require_once __DIR__ . &#39;/vendor/autoload.php&#39;;

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

class User
{
    // 模拟从数据库取数据
    public static function getUserLimit($limit)
    {
        $user  = [
            [
                "uid" => 1,
                "name" => "name1"
            ],
            [
                "uid" => 2,
                "name" => "name2"
            ],
            [
                "uid" => 3,
                "name" => "name3"
            ],
            [
                "uid" => 4,
                "name" => "name4"
            ]
        ];
        return array_slice($user, 0, $limit);
    }
}


$userType = new ObjectType([
    &#39;name&#39; => &#39;userType&#39;,
    &#39;description&#39; => &#39;用户详情&#39;,
    &#39;fields&#39; => [
        &#39;uid&#39; => [
            &#39;type&#39; => Type::int(),
            &#39;description&#39; => &#39;用户ID&#39;
        ],
        &#39;name&#39; => Type::string()
    ]
]);


$queryType = new ObjectType([
    &#39;name&#39; => &#39;Query&#39;,
    &#39;fields&#39; => [
        &#39;users&#39; => [
            &#39;type&#39; => Type::listOf($userType),
            &#39;description&#39; => &#39;用户列表&#39;,
            &#39;args&#39; => [
                &#39;limit&#39; => [
                    &#39;type&#39; => Type::int(),
                    &#39;description&#39; => &#39;限制条数&#39;,
                    &#39;defaultValue&#39; => 10
                ]
            ],
            &#39;resolve&#39; => function($root, $args) {
                return User::getUserLimit($args[&#39;limit&#39;]);
            }
        ]
    ]
]);



$schema = new Schema([
    &#39;query&#39; => $queryType
]);


$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);
$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [&#39;prefix&#39; => &#39;prefix: &#39;];
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {
    $output = [
        &#39;errors&#39; => [
            [
                &#39;message&#39; => $e->getMessage()
            ]
        ]
    ];
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사

执行示例代码结果

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

从上面结果可以看到,我们传了limit参数为2,最终从我们模拟的数据里面取出了2条数据

使用类型语言

在上面的示例中,如果我们代码返回的数据比较复杂时,需要编写大量的代码,通过GraphQL类型语言,我们可以减少代码量,使代码看上去更加简洁,这是一个用 GraphQL 类型语言定义的简单 Schema示例。

<?php

require_once __DIR__ . &#39;/vendor/autoload.php&#39;;
use GraphQL\GraphQL;
use GraphQL\Utils\BuildSchema;
// graph.graphql  文件内容
$graph =
<<<GRAPH
schema {
  query: Query
}

type Query {
  graph_test: String
  echo(message: String): String
  show_test: Show
  show_test_arr: [Show]
}


type Show {
    content: String!
    text: String!
}
GRAPH;


$schema = BuildSchema::build($graph);
$rawInput = file_get_contents(&#39;php://input&#39;);
$input = json_decode($rawInput, true);
$query = $input[&#39;query&#39;];
$variableValues = isset($input[&#39;variables&#39;]) ? $input[&#39;variables&#39;] : null;

try {
    $rootValue = [
        &#39;sum&#39; => function($rootValue, $args, $context) {
            return $args[&#39;x&#39;] + $args[&#39;y&#39;];
        },
        &#39;echo&#39; => function($rootValue, $args, $context) {
            return $rootValue[&#39;prefix&#39;] . ($args[&#39;message&#39;] ?? &#39;no echo&#39;);
        },
        &#39;show_test&#39; => function($rootValue, $args, $context) {
            return [
                &#39;content&#39; => &#39;show_content&#39;,
                &#39;text&#39; => &#39;xxxx xxx&#39;
            ];
        },
        &#39;show_test_arr&#39; => function($rootValue, $args, $context) {
            return [
                [
                    &#39;content&#39; => &#39;show_content&#39;,
                    &#39;text&#39; => &#39;xxxx xxx&#39;
                ],
                [
                    &#39;content&#39; => &#39;show_content_2&#39;,
                    &#39;text&#39; => &#39;xxxx xxx_2&#39;
                ]

            ];
        },
        &#39;prefix&#39; => &#39;from test:&#39;,
        "graph_test" => "graphql_test"
    ];;
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
    $output = $result->toArray();
} catch (\Exception $e) {

    \GraphQL\Server\StandardServer::send500Error($e);
}
header(&#39;Content-Type: application/json&#39;);
echo json_encode($output);
로그인 후 복사

执行示例代码结果

PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명

参考

graphql.cn/learn/

learnku.com/docs/graphq…

更多编程相关知识,请访问:编程视频!!

위 내용은 PHP에서 GraphQL을 설치하고 사용하는 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿