在ThinkPHP框架下使用GraphQL进行API发布和查询语言,需要进行以下步骤:
使用composer命令安装graphql-php和webonyx/graphql-php等相关依赖:
composer require graphql/graphql
composer require webonyx/graphql-php
在ThinkPHP的Controller目录下创建GraphQLController,并继承Think\Controller类,例如:
<?php
namespace app\index\controller;
use think\Controller;
use GraphQL\Type\Schema;
use GraphQL\GraphQL;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
class GraphQLController extends Controller
{
// ...
}
在GraphQLController中定义GraphQL Schema,例如:
$authorType = new ObjectType([
'name' => 'Author',
'fields' => [
'id' => Type::id(),
'name' => Type::string(),
'email' => Type::string(),
]
]);
$bookType = new ObjectType([
'name' => 'Book',
'fields' => [
'id' => Type::id(),
'title' => Type::string(),
'author' => $authorType,
]
]);
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'book' => [
'type' => $bookType,
'args' => [
'id' => Type::id(),
],
'resolve' => function ($root, $args) {
return getBookById($args['id']);
}
],
],
]);
$schema = new Schema([
'query' => $queryType,
]);
其中,$authorType和$bookType分别定义了作者和书籍的类型,$queryType定义了查询类型,$schema定义了整个GraphQL Schema。
在GraphQLController中处理GraphQL请求,例如:
public function index()
{
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput ?: '', true);
$query = isset($input['query']) ? $input['query'] : null;
$variableValues = isset($input['variables']) ? $input['variables'] : null;
try {
$result = GraphQL::executeQuery($schema, $query, null, null, $variableValues);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'error' => [
'message' => $e->getMessage()
]
];
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
}
其中,$rawInput获取请求的原始数据,$input解析请求数据,$query获取GraphQL查询语句,$variableValues获取GraphQL变量,GraphQL::executeQuery方法执行查询,$output输出GraphQL响应。
在ThinkPHP的路由文件中配置GraphQL路由,例如:
Route::any('/graphql', 'index/GraphQL/index');
至此,就可以在ThinkPHP框架下使用GraphQL进行API发布和查询语言了。