Generating PHP code for executing GraphQL
Install this package via Composer
composer require x-graphql/codegenAfter install, you need to generate config file with command bellow:
./vendor/bin/x-graphql-codegen x-graphql:codegen:init-configYour config file x-graphql-codegen.php initialized look like:
<?php
return [
'default' => [
/// PSR 4 namespace, classes and traits generated will use.
'namespace' => 'App\GraphQL\Codegen',
/// Where storing GraphQL queries files.
'sourcePath' => __DIR__ . '/',
/// Where storing PHP generated code with namespace above.
'destinationPath' => __DIR__ . '/',
/// Generated query class name.
'queryClassName' => 'GraphQLQuery',
]
];Edit it for suitable with your environment and create some graphql query files in sourcePath
then generate PHP code with command:
./vendor/bin/x-graphql-codegen x-graphql:codegen:generateAdd x-graphql/http-schema package for executing schema over http:
composer require x-graphql/http-schemaInit config file:
./vendor/bin/x-graphql-codegen x-graphql:codegen:init-configAdd example.graphql to your current working directory with content:
query getCountries {
countries {
name
}
}Run command to generate PHP code:
./vendor/bin/x-graphql-codegen x-graphql:codegen:generateUse generated query class:
<?php
require __DIR__ . '/vendor/autoload.php';
$delegator = new \XGraphQL\HttpSchema\HttpDelegator('https://countries.trevorblades.com/');
$schema = \XGraphQL\HttpSchema\HttpSchemaFactory::createFromIntrospectionQuery($delegator);
$query = new \App\GraphQL\Codegen\GraphQLQuery($schema);
$result = $query->getCountries();
var_dump($result->toArray());Created by Minh Vuong