本篇文章带大家了解一下GraphQL,并详细介绍PHP中安装和使用GraphQL的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
|
本篇文章带大家了解一下GraphQL,并详细介绍PHP中安装和使用GraphQL的方法。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
关于 GraphQLGraphQL 是一种现代化的 HTTP API 接口构建方式,客户端可以 与REST对比REST的核心思想就是资源,每个资源都能用一个URL来表示,你能通过一个GET请求访问该URL从而获取该资源。根据当今大多数API的定义,你很有可能会得到一份JSON格式的数据响应,整个过程大概是这样: GET /user/1
{
"username":"姓名",
"age":20,
"sex":"男"
}GET /book/1
{
"book":"书名",
"author":"作者",
"country":"中国"
}从上面的示例可以看出,如果前端需要 如果我们使用 query {
user(id:1) {
username
}
book(id:1){
book,
author,
country
}
}推荐学习:《PHP视频教程》 安装graphql-php包composer require webonyx/graphql-php 开始1、安装完成之后,我们先编写一个简单示例,来看看graphql-php怎么用,具体代码如下:这段代码中,我们定义了一个名为 <?php
require_once __DIR__ . '/vendor/autoload.php';
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'phoneNumber' => [
'type' => Type::int(),
'resolve' => function () {
return 1875555555;
}
]
],
]);
$schema = new Schema([
'query' => $queryType,
]);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = ['prefix' => 'prefix: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
header('Content-Type: application/json');
echo json_encode($output);2、使用postman来调用我们刚刚编写的代码,以下是我们查询结果的示例
介绍从上面的示例中,我们可以看到示例主要引入了4个类 use GraphQL\Type\Schema; use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; use GraphQL\GraphQL; Schema 类Schema 是类型层次结构的容器,它接受构造函数中的根类型并向内部 GrahpQL 工具提供接收你的类型信息的方法。 配置选项包含以下选项的数组:
ObjectType类GraphQL\Type\Definition\ObjectType 对象类型是典型的 GraphQL 应用程序中使用最频繁的基元。 配置选项
内置标量类型<?php use GraphQL\Type\Definition\Type; // 内置标量类型 Type::string(); // String 类型 Type::int(); // Int 类型 Type::float(); // Float 类型 Type::boolean(); // Boolean 类型 Type::id(); // ID 类型 字段参数GraphQL 对象类型上的所有字段都有 0 个或多个参数,使用在 args 的字段定义上。每个参数数组参考以下说明:
示例 $queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'phoneNumber' => [
'type' => Type::int(),
'resolve' => function () {
return 1875555555;
}
]
],
]);GraphQL 类GraphQL类主要在查询的时候用到,我们可以用 GraphQL::executeQuery 方法来执行查询 executeQuery 方法的参数说明
use GraphQL\GraphQL;
$result = GraphQL::executeQuery(
$schema,
$queryString,
$rootValue = null,
$context = null,
$variableValues = null,
$operationName = null,
$fieldResolver = null,
$validationRules = null
);简单示例我们介绍完GraphQL几个概念之后,用几个简单的示例带大家来体验一下。 普通示例在这个示例中我们定义了2个字段,分别是 <?php
require_once __DIR__ . '/vendor/autoload.php';
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'phoneNumber' => [
'type' => Type::int(),
'resolve' => function () {
return 1875555555;
}
],
'echo' => [
'type' => Type::string(),
'args' => [
'message' => Type::string(),
],
'resolve' => function ($root, $args) {
return 'echo msg result:' . ($args['message'] ?? 'nothing');
}
],
],
]);
$schema = new Schema([
'query' => $queryType
]);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = ['prefix' => 'prefix: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
header('Content-Type: application/json');
echo json_encode($output);执行示例代码结果
我们可以看到,在请求时我们传了 对象示例我们在上面说过,对象类型是典型的 GraphQL 应用程序中使用最频繁的基元,一个对象类型里面可以包含宁外一个对象类型,我们可以新定义一个名为 <?php
require_once __DIR__ . '/vendor/autoload.php';
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
$userType = new ObjectType([
'name' => 'userType',
'description' => '用户详情',
'fields' => [
'uid' => [
'type' => Type::int(),
'description' => '用户ID'
],
'name' => Type::string()
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'oneUser' => [
'type' => $userType, // 我们这里指定type为我们上面创建的$userType
'description' => '用户列表',
'args' => [
'uid' => [
'type' => Type::int(),
'defaultValue' => 222
]
],
'resolve' => function($root, $args) {
return [
"uid" => $args['user_id'] ?? 3,
"name" => "xzl",
];
}
],
]
]);
$schema = new Schema([
'query' => $queryType
]);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = ['prefix' => 'prefix: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
header('Content-Type: application/json');
echo json_encode($output);执行示例代码结果
列表示例在平时的开发请求中,我们从后端接口获取数据的时候,大部分都是以列表的形式返回的,我们可以通过 <?php
require_once __DIR__ . '/vendor/autoload.php';
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([
'name' => 'userType',
'description' => '用户详情',
'fields' => [
'uid' => [
'type' => Type::int(),
'description' => '用户ID'
],
'name' => Type::string()
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'users' => [
'type' => Type::listOf($userType),
'description' => '用户列表',
'args' => [
'limit' => [
'type' => Type::int(),
'description' => '限制条数',
'defaultValue' => 10
]
],
'resolve' => function($root, $args) {
return User::getUserLimit($args['limit']);
}
]
]
]);
$schema = new Schema([
'query' => $queryType
]);
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = ['prefix' => 'prefix: '];
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [
[
'message' => $e->getMessage()
]
]
];
}
header('Content-Type: application/json');
echo json_encode($output);执行示例代码结果
从上面结果可以看到,我们传了 使用类型语言在上面的示例中,如果我们代码返回的数据比较复杂时,需要编写大量的代码,通过GraphQL类型语言,我们可以减少代码量,使代码看上去更加简洁,这是一个用 GraphQL 类型语言定义的简单 Schema示例。 <?php
require_once __DIR__ . '/vendor/autoload.php';
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('php://input');
$input = json_decode($rawInput, true);
$query = $input['query'];
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$rootValue = [
'sum' => function($rootValue, $args, $context) {
return $args['x'] + $args['y'];
},
'echo' => function($rootValue, $args, $context) {
return $rootValue['prefix'] . ($args['message'] ?? 'no echo');
},
'show_test' => function($rootValue, $args, $context) {
return [
'content' => 'show_content',
'text' => 'xxxx xxx'
];
},
'show_test_arr' => function($rootValue, $args, $context) {
return [
[
'content' => 'show_content',
'text' => 'xxxx xxx'
],
[
'content' => 'show_content_2',
'text' => 'xxxx xxx_2'
]
];
},
'prefix' => 'from test:',
"graph_test" => "graphql_test"
];;
$result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
\GraphQL\Server\StandardServer::send500Error($e);
}
header('Content-Type: application/json');
echo json_encode($output);执行示例代码结果
参考graphql.cn/learn/ learnku.com/docs/graphq… 更多编程相关知识,请访问:编程视频!! 以上就是详解PHP中如何安装和使用GraphQL的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |
