项目作者: digiaonline

项目描述 :
A PHP7 implementation of the GraphQL specification.
高级语言: PHP
项目地址: git://github.com/digiaonline/graphql-php.git
创建时间: 2018-02-07T14:37:21Z
项目社区:https://github.com/digiaonline/graphql-php

开源协议:MIT License

下载


GraphQL

GitHub Actions status
Coverage Status
Scrutinizer Code Quality
License
Backers on Open Collective
Sponsors on Open Collective

This is a PHP implementation of the GraphQL specification based on the
JavaScript reference implementation.

Requirements

  • PHP version >= 7.1
  • ext-mbstring

Table of contents

Installation

Run the following command to install the package through Composer:

  1. composer require digiaonline/graphql

Example

Here is a simple example that demonstrates how to build an executable schema from a GraphQL schema file that contains
the Schema Definition Language (SDL) for a Star Wars-themed schema (for the schema definition itself, see below). In
this example we use that SDL to build an executable schema and use it to query for the name of the hero. The result
of that query is an associative array with a structure that resembles the query we ran.

  1. use Digia\GraphQL\Language\FileSourceBuilder;
  2. use function Digia\GraphQL\buildSchema;
  3. use function Digia\GraphQL\graphql;
  4. $sourceBuilder = new FileSourceBuilder(__DIR__ . '/star-wars.graphqls');
  5. $schema = buildSchema($sourceBuilder->build(), [
  6. 'Query' => [
  7. 'hero' => function ($rootValue, $arguments) {
  8. return getHero($arguments['episode'] ?? null);
  9. },
  10. ],
  11. ]);
  12. $result = graphql($schema, '
  13. query HeroNameQuery {
  14. hero {
  15. name
  16. }
  17. }');
  18. \print_r($result);

The script above produces the following output:

  1. Array
  2. (
  3. [data] => Array
  4. (
  5. [hero] => Array
  6. (
  7. [name] => "R2-D2"
  8. )
  9. )
  10. )

The GraphQL schema file used in this example contains the following:

```graphql schema
schema {
query: Query
}

type Query {
hero(episode: Episode): Character
human(id: String!): Human
droid(id: String!): Droid
}

interface Character {
id: String!
name: String
friends: [Character]
appearsIn: [Episode]
}

type Human implements Character {
id: String!
name: String
friends: [Character]
appearsIn: [Episode]
homePlanet: String
}

type Droid implements Character {
id: String!
name: String
friends: [Character]
appearsIn: [Episode]
primaryFunction: String
}

enum Episode { NEWHOPE, EMPIRE, JEDI }

  1. ## Creating a schema
  2. In order to execute queries against your GraphQL API, you first need to define the structure of your API. This is done
  3. by creating a schema. There are two ways to do this, you can either do it using SDL or you can do it programmatically.
  4. However, we strongly encourage you to use SDL, because it is easier to work with. To make an executable schema from
  5. SDL you need to call the `buildSchema` function.
  6. The `buildSchema` function takes three arguments:
  7. - `$source` The schema definition (SDL) as a `Source` instance
  8. - `$resolverRegistry` An associative array or a `ResolverRegistry` instance that contains all resolvers
  9. - `$options` The options for building the schema, which also includes custom types and directives
  10. To create the `Source` instance you can use the provided `FileSourceBuilder` or `MultiFileSourceBuilder` classes.
  11. ### Resolver registry
  12. The resolver registry is essentially a flat map with the type names as its keys and their corresponding resolver
  13. instances as its values. For smaller projects you can use an associative array and lambda functions to define your
  14. resolver registry. However, in larger projects we suggest that you implement your own resolvers instead. You can read
  15. more about resolvers under the [Resolvers](#resolvers) section.
  16. Associative array example:
  17. ```php
  18. $schema = buildSchema($source, [
  19. 'Query' => [
  20. 'hero' => function ($rootValue, $arguments) {
  21. return getHero($arguments['episode'] ?? null);
  22. },
  23. ],
  24. ]);

Resolver class example:

  1. $schema = buildSchema($source, [
  2. 'Query' => [
  3. 'hero' => new HeroResolver(),
  4. ],
  5. ]);

Resolver middleware

If you find yourself writing the same logic in multiple resolvers you should consider using middleware. Resolver
middleware allow you to efficiently manage functionality across multiple resolvers.

Before middleware example:

  1. $resolverRegistry = new ResolverRegristry([
  2. 'Query' => [
  3. 'hero' => function ($rootValue, $arguments) {
  4. return getHero($arguments['episode'] ?? null);
  5. },
  6. ],
  7. ], [
  8. 'middleware' => [new BeforeMiddleware()],
  9. ]);
  10. $schema = buildSchema($source, $resolverRegistry);
  1. class BeforeMiddleware implements ResolverMiddlewareInterface
  2. {
  3. public function resolve(callable $resolveCallback, $rootValue, array $arguments, $context, ResolveInfo $info) {
  4. $newRootValue = $this->doSomethingBefore();
  5. return $resolveCallback($newRootValue, $arguments, $context, $info);
  6. }
  7. }

After middleware example:

  1. $resolverRegistry = new ResolverRegristry([
  2. 'Query' => [
  3. 'hero' => function ($rootValue, $arguments) {
  4. return getHero($arguments['episode'] ?? null);
  5. },
  6. ],
  7. ], [
  8. 'middleware' => [new AfterMiddleware()],
  9. ]);
  10. $schema = buildSchema($source, $resolverRegistry);
  1. class AfterMiddleware implements ResolverMiddlewareInterface
  2. {
  3. public function resolve(callable $resolveCallback, $rootValue, array $arguments, $context, ResolveInfo $info) {
  4. $result = $resolveCallback($rootValue, $arguments, $context, $info);
  5. $this->doSomethingAfter();
  6. return $result;
  7. }
  8. }

Resolver middleware can be useful for a number of things; such as logging, input sanitization, performance
measurement, authorization and caching.

If you want to learn more about schemas you can refer to the specification.

Execution

Queries

To execute a query against your schema you need to call the graphql function and pass it your schema and the query
you wish to execute. You can also run mutations and subscriptions by changing your query.

  1. $query = '
  2. query HeroNameQuery {
  3. hero {
  4. name
  5. }
  6. }';
  7. $result = graphql($schema, $query);

If you want to learn more about queries you can refer to the specification.

Resolvers

Each type in a schema has a resolver associated with it that allows for resolving the actual value. However, most
types do not need a custom resolver, because they can be resolved using the default resolver. Usually these resolvers
are lambda functions, but you can also define your own resolvers by extending AbstractTypeResolver or AbstractFieldResolver. Alternatively you can also implement the ResolverInterface directly.

A resolver function receives four arguments:

  • $rootValue The parent object, which can also be null in some cases
  • $arguments The arguments provided to the field in the query
  • $context A value that is passed to every resolver that can hold important contextual information
  • $info A value which holds field-specific information relevant to the current query

Lambda function example:

  1. function ($rootValue, array $arguments, $context, ResolveInfo $info): string {
  2. return [
  3. 'type' => 'Human',
  4. 'id' => '1000',
  5. 'name' => 'Luke Skywalker',
  6. 'friends' => ['1002', '1003', '2000', '2001'],
  7. 'appearsIn' => ['NEWHOPE', 'EMPIRE', 'JEDI'],
  8. 'homePlanet' => 'Tatooine',
  9. ];
  10. }

Type resolver example:

  1. class HumanResolver extends AbstractTypeResolver
  2. {
  3. public function resolveName($rootValue, array $arguments, $context, ResolveInfo $info): string
  4. {
  5. return $rootValue['name'];
  6. }
  7. }

Field resolver example:

  1. class NameResolver extends AbstractFieldResolver
  2. {
  3. public function resolve($rootValue, array $arguments, $context, ResolveInfo $info): string
  4. {
  5. return $rootValue['name'];
  6. }
  7. }

The N+1 problem

The resolver function can return a value, a promise or an array of promises.
This resolver function below illustrates how to use promise to solve the N+1 problem, the full example can be found in
this test case.

  1. $movieType = newObjectType([
  2. 'fields' => [
  3. 'title' => ['type' => stringType()],
  4. 'director' => [
  5. 'type' => $directorType,
  6. 'resolve' => function ($movie, $args) {
  7. DirectorBuffer::add($movie['directorId']);
  8. return new Promise(function (callable $resolve, callable $reject) use ($movie) {
  9. DirectorBuffer::loadBuffered();
  10. $resolve(DirectorBuffer::get($movie['directorId']));
  11. });
  12. }
  13. ]
  14. ]
  15. ]);

Variables

You can pass in variables when executing a query by passing them to the graphql function.

  1. $query = '
  2. query HeroNameQuery($id: ID!) {
  3. hero(id: $id) {
  4. name
  5. }
  6. }';
  7. $variables = ['id' => '1000'];
  8. $result = graphql($schema, $query, null, null, $variables);

Context

In case you need to pass in some important contextual information to your queries you can use the $contextValues
argument on graphql to do so. This data will be passed to all of your resolvers as the $context argument.

  1. $contextValues = [
  2. 'currentlyLoggedInUser' => $currentlyLoggedInUser,
  3. ];
  4. $result = graphql($schema, $query, null, $contextValues, $variables);

Scalars

The leaf nodes in a schema are called scalars and each scalar resolves to some concrete data. The built-in, or
specified scalars in GraphQL are the following:

  • Boolean
  • Float
  • Int
  • ID
  • String

Custom scalars

In addition to the specified scalars you can also define your own custom scalars and let your schema know about
them by passing them to the buildSchema function as part of its $options argument.

Custom Date scalar type example:

  1. $dateType = newScalarType([
  2. 'name' => 'Date',
  3. 'serialize' => function ($value) {
  4. if ($value instanceof DateTime) {
  5. return $value->format('Y-m-d');
  6. }
  7. return null;
  8. },
  9. 'parseValue' => function ($value) {
  10. if (\is_string($value)){
  11. return new DateTime($value);
  12. }
  13. return null;
  14. },
  15. 'parseLiteral' => function ($node) {
  16. if ($node instanceof StringValueNode) {
  17. return new DateTime($node->getValue());
  18. }
  19. return null;
  20. },
  21. ]);
  22. $schema = buildSchema($source, [
  23. 'Query' => QueryResolver::class,
  24. [
  25. 'types' => [$dateType],
  26. ],
  27. ]);

Every scalar has to be coerced, which is done by three different functions. The serialize function converts a
PHP value into the corresponding output value. TheparseValue function converts a variable input value into the
corresponding PHP value and the parseLiteral function converts an AST literal into the corresponding PHP value.

Advanced usage

If you are looking for something that isn’t yet covered by this documentation your best bet is to take a look at the
tests in this project. You’ll be surprised how many examples you’ll find there.

Integration

Laravel

Here is an example that demonstrates how you can use this library in your Laravel project. You need an application
service to expose this library to your application, a service provider to register that service, a controller and a
route for handling the GraphQL POST requests.

app/GraphQL/GraphQLService.php

  1. class GraphQLService
  2. {
  3. private $schema;
  4. public function __construct(Schema $schema)
  5. {
  6. $this->schema = $schema;
  7. }
  8. public function executeQuery(string $query, array $variables, ?string $operationName): array
  9. {
  10. return graphql($this->schema, $query, null, null, $variables, $operationName);
  11. }
  12. }

app/GraphQL/GraphQLServiceProvider.php

  1. class GraphQLServiceProvider
  2. {
  3. public function register()
  4. {
  5. $this->app->singleton(GraphQLService::class, function () {
  6. $schemaDef = \file_get_contents(__DIR__ . '/schema.graphqls');
  7. $executableSchema = buildSchema($schemaDef, [
  8. 'Query' => QueryResolver::class,
  9. ]);
  10. return new GraphQLService($executableSchema);
  11. });
  12. }
  13. }

app/GraphQL/GraphQLController.php

  1. class GraphQLController extends Controller
  2. {
  3. private $graphqlService;
  4. public function __construct(GraphQLService $graphqlService)
  5. {
  6. $this->graphqlService = $graphqlService;
  7. }
  8. public function handle(Request $request): JsonResponse
  9. {
  10. $query = $request->get('query');
  11. $variables = $request->get('variables') ?? [];
  12. $operationName = $request->get('operationName');
  13. $result = $this->graphqlService->executeQuery($query, $variables, $operationName);
  14. return response()->json($result);
  15. }
  16. }

routes/api.php

  1. Route::post('/graphql', 'app\GraphQL\GraphQLController@handle');

Contributors

This project exists thanks to all the people who contribute. Contribute.

Backers

Thank you to all our backers! 🙏 Become a backer

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. Become a sponsor










License

See LICENCE.