|
| 1 | +# Interfaces |
| 2 | +An Interface is an abstract type that includes a certain set of fields that a type must include to implement the interface. |
| 3 | +An Interface can never be returned directly but must be implemented by 'child types'. |
| 4 | + |
| 5 | +**php-graphql** represents interfaces as instances of the class `GraphQLInterface`, which accepts several parameters |
| 6 | +in the constructor for configuring the interface. |
| 7 | + |
| 8 | +```php |
| 9 | +use GraphQL\Types\GraphQLInterface; |
| 10 | +use GraphQL\Fields\GraphQLTypeField; |
| 11 | +use GraphQL\Types\GraphQLNonNull; |
| 12 | +use GraphQL\Types\GraphQLString; |
| 13 | +use GraphQL\Types\GraphQLList; |
| 14 | + |
| 15 | +$Character = new GraphQLInterface("Character", "A character in the Star Wars Trilogy.", function () use (&$Character, &$Episode) { |
| 16 | + return [ |
| 17 | + new GraphQLTypeField("id", new GraphQLNonNull(new GraphQLString()), "The id of the character."), |
| 18 | + new GraphQLTypeField("name", new GraphQLString(), "The name of the character."), |
| 19 | + new GraphQLTypeField("friends", new GraphQLList($Character), "The friends of the character, or an empty list if they have none."), |
| 20 | + new GraphQLTypeField("appearsIn", new GraphQLList($Episode), "Which movies they appear in."), |
| 21 | + ]; |
| 22 | +}, function ($character) { |
| 23 | + if ($character["type"] === "human") { |
| 24 | + return "Human"; |
| 25 | + } |
| 26 | + return "Droid"; |
| 27 | +}); |
| 28 | +``` |
| 29 | +# GraphQLInterface Constructor |
| 30 | +Parameters used for the `GraphQLInterface` constructors are (in the following order): |
| 31 | + |
| 32 | +| Parameter | Type | Description | Required | |
| 33 | +| --- | --- | --- | --- | |
| 34 | +| **type** | `string` | Name of the new interface. Used for introspection. | ☑️ | |
| 35 | +| **description** | `string` | Description of the new interface. Used for introspection. | ☑️ | |
| 36 | +| **fields** | `\Closure` | Function that returns an array of `GraphQLTypeField`. Each field must be implemented in the type that implements this interface. Is called as soon the fields are needed. Used during validation and execution. | ☑️ | |
| 37 | +| **resolveTypeFn** | `\Closure` | Function that decides to which implementing object type a data object belongs to. If not passed, the default resolver is used. Used during validation and execution. | ️ | |
| 38 | + |
| 39 | + |
| 40 | +# Implementing Interfaces |
| 41 | +Interfaces can be implemented by a `GraphQLObjectType`, when passing the interface (reference) to the `GraphQLObjectType` constructor (see parameters of `GraphQLObjectType` constructor in the according section). |
0 commit comments