企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[toc] #### 预备知识 本文档假定您熟悉GraphQL概念,如果没有,可以先学[官网](http://graphql.org/learn/)的GraphQL介绍。 #### 安装 Using [composer](https://getcomposer.org/doc/00-intro.md),`composer.json` ~~~ { "require": { "webonyx/graphql-php": "^0.8" } } ~~~ #### 更新 [upgrade instructions](https://github.com/webonyx/graphql-php/blob/master/UPGRADE.md) #### 安装工具(可选) 虽然可以使用常规的`HTTP`与`GraphQL API`通讯,但是使用[`GraphiQL`](https://github.com/graphql/graphiql),用浏览器内的工具探索`GraphQL APIs` 更方便的方式是安装chrome 扩展。 * [ GraphiQL Feen](https://chrome.google.com/webstore/detail/graphiql-feen/mcbfdonlkfpbfdpimkjilhdneikhfklp) * [ChromeiQL](https://chrome.google.com/webstore/detail/chromeiql/fkkiamalmpiidkljmicmjfbieiclmeij) #### Hello World 让我们创建类型系统来处理下面的简单查询。 ~~~ query { echo(message: "Hello World") } ~~~ 为此我们需要定义带有字段`echo`的对象类型。 ~~~ use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'echo' => [ 'type' => Type::string(), 'args' => [ 'message' => Type::nonNull(Type::string()), ], 'resolve' => function ($root, $args) { return $root['prefix'] . $args['message']; } ], ], ]); ~~~ (Note:类型定义能够使用不同的方式,这里为了简单使用内联方式定义) 有意思的部分是这里字段定义的`resolve`选项,它负责返回字段的值,`scalar`类型字段的值会直接包含到响应中,然而如果是`complex`类型(`objects`, `interfaces`, `unions`)的值会被传给它下面嵌套的字段解析器。 现在类型已经准备好,让我们创建GraphQL服务端点。 ~~~ use GraphQL\GraphQL; use GraphQL\Schema; $schema = new Schema([ 'query' => $queryType ]); $rawInput = file_get_contents('php://input'); try { $rootValue = ['prefix' => 'You said: ']; $result = GraphQL::execute($schema, $rawInput, $rootValue); } catch (\Exception $e) { $result = [ 'error' => [ 'message' => $e->getMessage() ] ]; } header('Content-Type: application/json; charset=UTF-8'); echo json_encode($result); ~~~ 运行代码 ~~~ php -S localhost:8000 graphql.php curl http://localhost:8000 -d "query { echo(message: \"Hello World\") }" ~~~ hello world示例只是很简单的例子,可以查看下一例子,它更接近现实生活的应用程序。 #### Blog Example 通过更容易从全功能的例子开始,然后返回文档开始你自己的工作。