PHP GraphQL库:webonyx/graphql-php 与 Lighthouse
GraphQL是一种API查询语言,允许客户端仅请求所需的数据。在PHP生态系统中,实现GraphQL的主要库是webonyx/graphql-php。它提供了一套完整的工具,用于创建模式、类型和解析器。对于Laravel框架,有Lighthouse包,它扩展了graphql-php的功能并简化了开发。
安装 webonyx/graphql-php
通过Composer进行安装:
composer require webonyx/graphql-php创建模式与类型
GraphQL的基础是模式,它定义了数据类型及其相互关系。我们来看一个创建简单模式以获取用户列表的示例。
<?phpuse GraphQL\\Type\\Definition\\ObjectType;use GraphQL\\Type\\Definition\\Type;use GraphQL\\Type\\Schema;use GraphQL\\GraphQL;
// 定义User类型$userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::int(), 'name' => Type::string(), 'email' => Type::string(), ]]);
// 定义Query类型(查询的根类型)$queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'user' => [ 'type' => $userType, 'args' => [ 'id' => Type::nonNull(Type::int()) ], 'resolve' => function ($root, $args) { // 示例数据 - 实际项目中此处将查询数据库 $users = [ 1 => ['id' => 1, 'name' => '伊万', 'email' => 'ivan@example.com'], 2 => ['id' => 2, 'name' => '玛丽亚', 'email' => 'maria@example.com'], ]; return $users[$args['id']] ?? null; } ], 'users' => [ 'type' => Type::listOf($userType), 'resolve' => function () { return [ ['id' => 1, 'name' => '伊万', 'email' => 'ivan@example.com'], ['id' => 2, 'name' => '玛丽亚', 'email' => 'maria@example.com'], ]; } ] ]]);
// 创建模式$schema = new Schema([ 'query' => $queryType]);
// 执行查询$rawInput = file_get_contents('php://input');$input = json_decode($rawInput, true);$query = $input['query'];$result = GraphQL::executeQuery($schema, $query);$output = $result->toArray();
header('Content-Type: application/json');echo json_encode($output);使用变更(Mutation)
除了查询(Query),GraphQL还支持变更(Mutation)来修改数据。以下是创建添加用户变更的示例:
<?php// 定义变更类型$mutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ 'addUser' => [ 'type' => $userType, 'args' => [ 'name' => Type::nonNull(Type::string()), 'email' => Type::nonNull(Type::string()) ], 'resolve' => function ($root, $args) { // 此处应为保存到数据库的代码 return [ 'id' => 3, 'name' => $args['name'], 'email' => $args['email'] ]; } ] ]]);
// 更新模式$schema = new Schema([ 'query' => $queryType, 'mutation' => $mutationType]);在Laravel中使用Lighthouse
如果您使用Laravel,建议使用Lighthouse。它基于Eloquent模型自动创建模式,并提供