PHP code example of hsd-tech / graphql
1. Go to this page and download the library: Download hsd-tech/graphql library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hsd-tech / graphql example snippets
use Digia\GraphQL\Language\FileSourceBuilder;
use function Digia\GraphQL\buildSchema;
use function Digia\GraphQL\graphql;
$sourceBuilder = new FileSourceBuilder(__DIR__ . '/star-wars.graphqls');
$schema = buildSchema($sourceBuilder->build(), [
'Query' => [
'hero' => function ($rootValue, $arguments) {
return getHero($arguments['episode'] ?? null);
},
],
]);
$result = graphql($schema, '
query HeroNameQuery {
hero {
name
}
}');
\print_r($result);
Array
(
[data] => Array
(
[hero] => Array
(
[name] => "R2-D2"
)
)
)
$schema = buildSchema($source, [
'Query' => [
'hero' => function ($rootValue, $arguments) {
return getHero($arguments['episode'] ?? null);
},
],
]);
$schema = buildSchema($source, [
'Query' => [
'hero' => new HeroResolver(),
],
]);
$schema = buildSchema($source, [
'Query' => [
'hero' => function ($rootValue, $arguments) {
return getHero($arguments['episode'] ?? null);
},
],
], [
'middleware' => [new BeforeMiddleware()],
]);
class BeforeMiddleware implements ResolverMiddlewareInterface
{
public function resolve(callable $resolveCallback, $rootValue, array $arguments, $context, ResolveInfo $info) {
$newRootValue = $this->doSomethingBefore();
return $resolveCallback($newRootValue, $arguments, $context, $info);
}
}
$schema = buildSchema($source, [
'Query' => [
'hero' => function ($rootValue, $arguments) {
return getHero($arguments['episode'] ?? null);
},
],
], [
'middleware' => [new AfterMiddleware()],
]);
class AfterMiddleware implements ResolverMiddlewareInterface
{
public function resolve(callable $resolveCallback, $rootValue, array $arguments, $context, ResolveInfo $info) {
$result = $resolveCallback($rootValue, $arguments, $context, $info);
$this->doSomethingAfter();
return $result;
}
}
$query = '
query HeroNameQuery {
hero {
name
}
}';
$result = graphql($schema, $query);
function ($rootValue, array $arguments, $context, ResolveInfo $info): string {
return [
'type' => 'Human',
'id' => '1000',
'name' => 'Luke Skywalker',
'friends' => ['1002', '1003', '2000', '2001'],
'appearsIn' => ['NEWHOPE', 'EMPIRE', 'JEDI'],
'homePlanet' => 'Tatooine',
];
}
class HumanResolver extends AbstractTypeResolver
{
public function resolveName($rootValue, array $arguments, $context, ResolveInfo $info): string
{
return $rootValue['name'];
}
}
class NameResolver extends AbstractFieldResolver
{
public function resolve($rootValue, array $arguments, $context, ResolveInfo $info): string
{
return $rootValue['name'];
}
}
$movieType = newObjectType([
'fields' => [
'title' => ['type' => stringType()],
'director' => [
'type' => $directorType,
'resolve' => function ($movie, $args) {
DirectorBuffer::add($movie['directorId']);
return new Promise(function (callable $resolve, callable $reject) use ($movie) {
DirectorBuffer::loadBuffered();
$resolve(DirectorBuffer::get($movie['directorId']));
});
}
]
]
]);
$query = '
query HeroNameQuery($id: ID!) {
hero(id: $id) {
name
}
}';
$variables = ['id' => '1000'];
$result = graphql($schema, $query, null, null, $variables);
$contextValues = [
'currentlyLoggedInUser' => $currentlyLoggedInUser,
];
$result = graphql($schema, $query, null, $contextValues, $variables);
$dateType = newScalarType([
'name' => 'Date',
'serialize' => function ($value) {
if ($value instanceof DateTime) {
return $value->format('Y-m-d');
}
return null;
},
'parseValue' => function ($value) {
if (\is_string($value)){
return new DateTime($value);
}
return null;
},
'parseLiteral' => function ($node) {
if ($node instanceof StringValueNode) {
return new DateTime($node->getValue());
}
return null;
},
]);
$schema = buildSchema($source, [
'Query' => QueryResolver::class,
[
'types' => [$dateType],
],
]);
class GraphQLService
{
private $schema;
public function __construct(Schema $schema)
{
$this->schema = $schema;
}
public function executeQuery(string $query, array $variables, ?string $operationName): array
{
return graphql($this->schema, $query, null, null, $variables, $operationName);
}
}
class GraphQLServiceProvider
{
public function register()
{
$this->app->singleton(GraphQLService::class, function () {
$schemaDef = \file_get_contents(__DIR__ . '/schema.graphqls');
$executableSchema = buildSchema($schemaDef, [
'Query' => QueryResolver::class,
]);
return new GraphQLService($executableSchema);
});
}
}
class GraphQLController extends Controller
{
private $graphqlService;
public function __construct(GraphQLService $graphqlService)
{
$this->graphqlService = $graphqlService;
}
public function handle(Request $request): JsonResponse
{
$query = $request->get('query');
$variables = $request->get('variables') ?? [];
$operationName = $request->get('operationName');
$result = $this->graphqlService->executeQuery($query, $variables, $operationName);
return response()->json($result);
}
}
Route::post('/graphql', 'app\GraphQL\GraphQLController@handle');