PHP的GraphQL库:webonyx/graphql-php
GraphQL是一种由Facebook开发的现代API查询语言。在PHP中,实现GraphQL最流行且成熟的库之一是webonyx/graphql-php。该库允许开发者创建灵活、类型化且高效的API,使客户端能够仅请求所需的数据。
在本文中,我们将详细介绍如何在您的PHP项目中安装、配置和使用webonyx/graphql-php。该库完全实现了GraphQL官方规范(2018年6月版),并支持所有现代功能:查询(queries)、变更(mutations)、订阅(subscriptions)、接口、联合类型等等。
安装与配置
通过Composer进行安装。在项目根目录打开终端并执行:
composer require webonyx/graphql-php安装完成后,该库即可使用。无需最低配置——只需在您的PHP文件中导入所需的类即可。
库的主要组件
该库由几个相互协作的关键组件组成:
- 模式(Schema)——定义数据类型和可用操作(查询和变更)。
- 类型(Types)——描述数据结构(ObjectType、ScalarType、EnumType、InterfaceType、UnionType等)。
- 解析器(Resolvers)——为每个字段返回数据的函数。
- 执行器(Executor)——处理传入请求并返回结果。
创建简单模式
让我们看一个创建用于处理用户的简单GraphQL模式的示例。首先定义User类型:
<?phpuse GraphQL\\Type\\Definition\\ObjectType;use GraphQL\\Type\\Definition\\Type;
$userType = new ObjectType([ 'name' => 'User', 'fields' => [ 'id' => Type::int(), 'name' => Type::string(), 'email' => Type::string(), 'age' => Type::int(), ],]);现在创建根查询类型Query,它将返回用户列表:
$queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'users' => [ 'type' => Type::listOf($userType), 'resolve' => function ($root, $args) { // 这里通常是数据库查询 return [ ['id' => 1, 'name' => '伊万·伊万诺夫', 'email' => 'ivan@example.com', 'age' => 30], ['id' => 2, 'name' => '玛丽亚·彼得罗娃', 'email' => 'maria@example.com', 'age' => 25], ]; }, ], 'user' => [ 'type' => $userType, 'args' => [ 'id' => Type::nonNull(Type::int()), ], 'resolve' => function ($root, $args) { // 根据ID查找用户 $users = [ 1 => ['id' => 1, 'name' => '伊万·伊万诺夫', 'email' => 'ivan@example.com', 'age' => 30], 2 => ['id' => 2, 'name' => '玛丽亚·彼得罗娃', 'email' => 'maria@example.com', 'age' => 25], ]; return $users[$args['id']] ?? null; }, ], ],]);整合到模式中并执行查询
现在将所有内容整合到一个模式中并执行测试查询:
use GraphQL\\GraphQL;use GraphQL\\Schema;
$schema = new Schema([ 'query' => $queryType,]);
// 传入的GraphQL查询(通常通过POST发送)$query = '{ users { id name em