扩展
Internal GraphQL Server
使用 PHP 代码在应用程序内部直接执行 GraphQL queries。

此扩展会安装一个内部 GraphQL Server,可通过 PHP 代码在应用程序内部调用。
内部 GraphQL Server 通过类 GatoGraphQL\InternalGraphQLServer\GraphQLServer 访问,提供以下三个方法:
executeQuery:执行一个 GraphQL queryexecuteQueryInFile:执行包含在 (.gql) 文件中的 GraphQL queryexecutePersistedQuery:执行已保存的 GraphQL query(以整数形式提供 ID,或以字符串形式提供 slug)(需要 Persisted Queries 扩展)
方法签名如下:
namespace GatoGraphQL\InternalGraphQLServer;
use PoP\Root\HttpFoundation\Response;
class GraphQLServer {
/**
* Execute a GraphQL query
*/
public static function executeQuery(
string $query,
array $variables = [],
?string $operationName = null,
int|string|null $schemaConfigurationIDOrSlug = null,
): Response {
// ...
}
/**
* Execute a GraphQL query contained in a (`.gql`) file
*/
public static function executeQueryInFile(
string $file,
array $variables = [],
?string $operationName = null,
int|string|null $schemaConfigurationIDOrSlug = null,
): Response {
// ...
}
/**
* Execute a persisted GraphQL query (providing its object
* of type WP_Post, ID as an int, or slug as a string)
*/
public static function executePersistedQuery(
WP_Post|string|int $persistedQuery,
array $variables = [],
?string $operationName = null
): Response {
// ...
}
}执行 GraphQL query 并获取响应内容:
use GatoGraphQL\InternalGraphQLServer\GraphQLServer;
// Provide the GraphQL query
$query = "{ ... }";
// Execute the query against the internal server
$response = GraphQLServer::executeQuery($query);
// Get the content and decode it
$responseContent = json_decode($response->getContent(), true);
// Access the data and errors from the response
$responseData = $responseContent["data"] ?? [];
$responseErrors = $responseContent["errors"] ?? [];