graphql-php,入门 · graphql-php · 看云

[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

通过更容易从全功能的例子开始,然后返回文档开始你自己的工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值