Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GraphQL example for webonyx/graphql-php library
<?php
require_once 'vendor/autoload.php';
use GraphQL\GraphQL;
use GraphQL\Type\Schema;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Server\StandardServer;
use Laminas\Diactoros\ServerRequestFactory;
use GraphQL\Server\ServerConfig;
use GraphQL\Error\DebugFlag;
$flats_item = new ObjectType(
[
'name' => 'FlatItem',
'fields' => [
'id' => Type::int(),
'floor' => Type::int(),
'num' => Type::int(),
'price' => Type::int(),
'area_total' => Type::int(),
'complex' => Type::string()
]
]
);
$flats_items = new ObjectType(
[
'name' => 'FlatsItems',
'fields' => [
'items' => Type::listof($flats_item)
]
]
);
$flats = [
'type' => $flats_items,
'args' => [
'price_min' => Type::int(),
'price_max' => Type::int(),
],
'resolve' => function ($rootValue, $args) {
$flats = [
[
'id' => 1,
'floor' => 2,
'num' => 3,
'price' => 100,
'area_total' => 10,
'complex' => 'Complex 1'
],
[
'id' => 2,
'floor' => 2,
'num' => 3,
'price' => 200,
'area_total' => 10,
'complex' => 'Complex 2'
],
[
'id' => 3,
'floor' => 2,
'num' => 3,
'price' => 300,
'area_total' => 10,
'complex' => 'Complex 3'
],
[
'id' => 3,
'floor' => 2,
'num' => 3,
'price' => 400,
'area_total' => 10,
'complex' => 'Complex 1'
],
];
return ['items' => array_filter($flats,function($flat) use ($args) {
if($flat['price']>$args['price_min'])
return true;
else
return false;
})];
}
];
$query = new ObjectType([
'name' => 'Query',
'fields' => [
'flats' => $flats,
]
]);
$schema = new Schema([
'query' => $query,
]);
$server_config = ServerConfig::create()
->setSchema($schema);
$request = ServerRequestFactory::fromGlobals();
$rawInput = file_get_contents('php://input');
$input = json_decode($rawInput, true);
$request = $request->withParsedBody($input);
$server = new StandardServer($server_config);
$result = $server->executePsrRequest($request);
@razorback21
Copy link

razorback21 commented Feb 14, 2022

I follow this but I have an error. The schema does not define the required query root type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment