Skip to content

Commit 199caf3

Browse files
committed
New example for server usage
1 parent 71343f2 commit 199caf3

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

examples/03-server/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Hello world
2+
Same example as 01-hello-world, but uses
3+
[Standard Http Server](http://webonyx.github.io/graphql-php/executing-queries/#using-server)
4+
instead of manual parsing of incoming data.
5+
6+
### Run locally
7+
```
8+
php -S localhost:8080 ./graphql.php
9+
```
10+
11+
### Try query
12+
```
13+
curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
14+
```
15+
16+
### Try mutation
17+
```
18+
curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
19+
```

examples/03-server/graphql.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
// Test this using following command
3+
// php -S localhost:8080 ./graphql.php &
4+
// curl http://localhost:8080 -d '{"query": "query { echo(message: \"Hello World\") }" }'
5+
// curl http://localhost:8080 -d '{"query": "mutation { sum(x: 2, y: 2) }" }'
6+
require_once __DIR__ . '/../../vendor/autoload.php';
7+
8+
use GraphQL\Type\Definition\ObjectType;
9+
use GraphQL\Type\Definition\Type;
10+
use GraphQL\Type\Schema;
11+
use GraphQL\Server\StandardServer;
12+
13+
try {
14+
$queryType = new ObjectType([
15+
'name' => 'Query',
16+
'fields' => [
17+
'echo' => [
18+
'type' => Type::string(),
19+
'args' => [
20+
'message' => ['type' => Type::string()],
21+
],
22+
'resolve' => function ($root, $args) {
23+
return $root['prefix'] . $args['message'];
24+
}
25+
],
26+
],
27+
]);
28+
29+
$mutationType = new ObjectType([
30+
'name' => 'Calc',
31+
'fields' => [
32+
'sum' => [
33+
'type' => Type::int(),
34+
'args' => [
35+
'x' => ['type' => Type::int()],
36+
'y' => ['type' => Type::int()],
37+
],
38+
'resolve' => function ($root, $args) {
39+
return $args['x'] + $args['y'];
40+
},
41+
],
42+
],
43+
]);
44+
45+
// See docs on schema options:
46+
// http://webonyx.github.io/graphql-php/type-system/schema/#configuration-options
47+
$schema = new Schema([
48+
'query' => $queryType,
49+
'mutation' => $mutationType,
50+
]);
51+
52+
// See docs on server options:
53+
// http://webonyx.github.io/graphql-php/executing-queries/#server-configuration-options
54+
$server = new StandardServer([
55+
'schema' => $schema
56+
]);
57+
58+
$server->handleRequest();
59+
} catch (\Exception $e) {
60+
StandardServer::send500Error($e);
61+
}

0 commit comments

Comments
 (0)