x-graphql/codegen

Generating PHP code for executing GraphQL

0.1.0 2024-03-27 10:27 UTC

This package is auto-updated.

Last update: 2024-04-27 10:42:16 UTC


README

Generating PHP code for executing GraphQL

unit tests codecov

Getting Started

Install this package via Composer

composer require x-graphql/codegen

Usages

After install, you need to generate config file with command bellow:

./vendor/bin/x-graphql-codegen x-graphql:codegen:init-config

Your 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:generate

Example

Add x-graphql/http-schema package for executing schema over http:

composer require x-graphql/http-schema

Init config file:

./vendor/bin/x-graphql-codegen x-graphql:codegen:init-config

Add 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:generate

Use 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());

Credits

Created by Minh Vuong