Directives
GraphQL directives annotate the schema with extra information (@deprecated, @oneOf, ...) and can
change how a part of it behaves. In GraphQLite, a directive is a PHP attribute class: you declare it
once, then put it on your types, fields and input fields like any other attribute.
GraphQLite ships with bindings for the built-in GraphQL directives, and lets you define your own.
Built-in directives
#[Deprecated]
#[Deprecated] marks a query, mutation, subscription or field as deprecated. It maps to the
@deprecated directive of the GraphQL specification.
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;
use TheCodingMachine\GraphQLite\Directives\BuiltIn\Deprecated;
#[Type]
class Product
{
#[Field]
public function getName(): string { /* ... */ }
#[Field]
#[Deprecated(reason: 'Use `name` instead.')]
public function getProductName(): string { /* ... */ }
}
type Product {
name: String!
productName: String! @deprecated(reason: "Use `name` instead.")
}
The reason argument is optional:
- with a
reason, that reason is used. - without one, the reason of a
@deprecateddocblock tag on the same method is used (see deprecating fields). - with neither, the GraphQL default reason (
"No longer supported") is used.
The @deprecated docblock tag keeps working on its own. #[Deprecated] is useful when the reason you
want to show to API consumers differs from the one meant for PHP developers, or when you don't want a
PHP-level deprecation at all.
#[OneOf]
#[OneOf] turns an input type into a OneOf input object:
the client must provide exactly one of its fields, and that field must not be null. It maps to the
@oneOf directive.
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Input;
use TheCodingMachine\GraphQLite\Directives\BuiltIn\OneOf;
#[Input]
#[OneOf]
class ProductLookup
{
public function __construct(
#[Field]
public string|null $sku = null,
#[Field]
public int|null $id = null,
) {
}
}
input ProductLookupInput @oneOf {
sku: String
id: Int
}
# Valid
{ product(lookup: { sku: "ABC-123" }) { name } }
# Invalid: two fields are set
{ product(lookup: { sku: "ABC-123", id: 42 }) { name } }
GraphQL validates the input before your resolver runs, so your code can rely on exactly one of the properties being set. The fields of a OneOf input must be nullable, and their default values are dropped from the schema (the spec does not allow them).
#[OneOf] is only valid on #[Input] classes. Putting it on a #[Type] throws an
InvalidDirectiveException when the schema is built.
Other specification directives
@skip, @include and @specifiedBy are provided by the underlying webonyx/graphql-php library and
work out of the box. @skip and @include are used by clients in their queries; GraphQLite has
nothing to bind for them.
Custom directives
Declaring a directive
A directive is a class that:
- is a PHP attribute (
#[Attribute(...)]), - implements one of the directive interfaces below,
- returns its GraphQL definition from a static
definition()method.
namespace App\GraphQL\Directives;
use Attribute;
use TheCodingMachine\GraphQLite\Directives\DirectiveDefinition;
use TheCodingMachine\GraphQLite\Directives\DirectiveLocation;
use TheCodingMachine\GraphQLite\Directives\FieldDirective;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY)]
final class Internal implements FieldDirective
{
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(
name: 'internal',
locations: [DirectiveLocation::FIELD_DEFINITION],
description: 'The field is meant for internal clients only.',
);
}
}
That's it. There is nothing to register: GraphQLite discovers directive classes in the namespaces you
already pass to SchemaFactory::addNamespace() (or the equivalent setting of the Symfony bundle or
Laravel package). Discovered directives are cached like the rest of the schema.
The directive is now part of the schema:
"The field is meant for internal clients only."
directive @internal on FIELD_DEFINITION
and can be applied:
#[Type]
class Product
{
#[Field]
#[Internal]
public function getCostPrice(): float { /* ... */ }
}
Locations and interfaces
A directive declares where it can be used through DirectiveDefinition::$locations. GraphQLite
currently supports four locations, each paired with an interface and with the PHP attribute targets
the class must allow:
| Location | Interface | Used on | Required #[Attribute] targets |
|---|---|---|---|
FIELD_DEFINITION | FieldDirective | #[Field], #[Query], #[Mutation], #[Subscription] | TARGET_METHOD, TARGET_PROPERTY |
INPUT_FIELD_DEFINITION | InputFieldDirective | #[Field] of an #[Input] class | TARGET_METHOD, TARGET_PROPERTY, TARGET_PARAMETER |
OBJECT | ObjectTypeDirective | #[Type] classes | TARGET_CLASS |
INPUT_OBJECT | InputObjectTypeDirective | #[Input] classes | TARGET_CLASS |
All the interfaces live in the TheCodingMachine\GraphQLite\Directives namespace.
A directive can support several locations by implementing several interfaces and listing every matching location:
#[Attribute(Attribute::TARGET_CLASS)]
final class Owner implements ObjectTypeDirective, InputObjectTypeDirective
{
public function __construct(public readonly string $team)
{
}
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(
name: 'owner',
locations: [DirectiveLocation::OBJECT, DirectiveLocation::INPUT_OBJECT],
);
}
}
The interfaces and the locations must agree, and the PHP targets must cover every location. Any
mismatch throws an InvalidDirectiveException when the schema is built, with a message that says
what to fix.
These four are the only locations a directive can declare. A directive that lists any other location
(a type-system one such as ENUM or ARGUMENT_DEFINITION, or an executable one such as FIELD), or
that lists no location at all, throws an InvalidDirectiveException naming the class, the unsupported
locations and the supported ones. Without this check, the directive would be published in the schema
but never applied. A builtIn: true directive (see naming rules) may also list the
other locations of webonyx/graphql-php's definition of it, because webonyx publishes that definition,
but it still needs one of the four.
Arguments
The constructor parameters of the directive class become the arguments of the directive:
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY)]
final class CacheControl implements FieldDirective
{
public function __construct(
public readonly int $maxAge,
public readonly bool $private = false,
public readonly string|null $scope = null,
) {
}
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(
name: 'cacheControl',
locations: [DirectiveLocation::FIELD_DEFINITION],
);
}
}
directive @cacheControl(maxAge: Int!, private: Boolean! = false, scope: String = null) on FIELD_DEFINITION
- Supported PHP types are
string,int,floatandbool, mapped toString,Int,FloatandBoolean. - A nullable PHP type gives a nullable argument; otherwise the argument is non-null.
- A PHP default value becomes the argument's default value.
Each argument's value is read from the property of the same name, so use constructor property promotion (as above) or assign a property with the same name as the parameter.
Repeatable directives
Add Attribute::IS_REPEATABLE to make the directive repeatable, both in PHP and in GraphQL:
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class Audit implements FieldDirective
{
public function __construct(public readonly string $reason)
{
}
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(name: 'audit', locations: [DirectiveLocation::FIELD_DEFINITION]);
}
}
#[Field]
#[Audit(reason: 'pii')]
#[Audit(reason: 'compliance')]
public function getEmail(): string { /* ... */ }
directive @audit(reason: String!) repeatable on FIELD_DEFINITION
Metadata directives
A directive that only implements one of the interfaces above is a metadata directive: it is declared in the schema and attached to the elements it is applied to, but it doesn't change how they behave. Use it to tag your schema for PHP code that reads the built schema on the server.
Where a directive shows up:
- Its definition (
directive @internal on FIELD_DEFINITION) is part of the schema: it is returned by introspection and printed by webonyx/graphql-php'sSchemaPrinter. - The places where it is applied are not. The GraphQL specification doesn't expose them through
introspection, and
SchemaPrinterdoesn't print them (it only prints@deprecated,@oneOfand@specifiedBy, from their own properties). Clients and tools that read the schema through introspection or printed SDL don't see them.
GraphQLite stores the applications on the astNode of each schema element, so server-side code can
read them from the built schema:
$schema = $schemaFactory->createSchema();
$type = $schema->getType('Product');
foreach ($type->getField('costPrice')->astNode->directives as $directive) {
echo $directive->name->value; // "internal"
}
Behavioral directives
To make a directive do something, implement the behavioral variant of its interface:
| Interface | Method |
|---|---|
BehavioralFieldDirective | applyToField(QueryFieldDescriptor $descriptor, FieldHandlerInterface $next): ?FieldDefinition |
BehavioralInputFieldDirective | applyToInputField(InputFieldDescriptor $descriptor, InputFieldHandlerInterface $next): ?InputField |
BehavioralObjectTypeDirective | applyToObjectType(ObjectTypeDescriptor $descriptor, ObjectTypeHandlerInterface $next): MutableObjectType |
BehavioralInputObjectTypeDirective | applyToInputObjectType(InputObjectTypeDescriptor $descriptor, InputObjectTypeHandlerInterface $next): MutableInputObjectType |
These methods run while the schema is built and work like
field middlewares: change the descriptor, then pass it to $next, or change
what $next returns. When an element carries several behavioral directives, they run in the order
they are declared.
Wrapping a field resolver
The most common use is wrapping the resolver of a field:
use Attribute;
use GraphQL\Type\Definition\FieldDefinition;
use TheCodingMachine\GraphQLite\Directives\BehavioralFieldDirective;
use TheCodingMachine\GraphQLite\Directives\DirectiveDefinition;
use TheCodingMachine\GraphQLite\Directives\DirectiveLocation;
use TheCodingMachine\GraphQLite\Middlewares\FieldHandlerInterface;
use TheCodingMachine\GraphQLite\QueryFieldDescriptor;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_PROPERTY)]
final class Uppercase implements BehavioralFieldDirective
{
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(name: 'uppercase', locations: [DirectiveLocation::FIELD_DEFINITION]);
}
public function applyToField(QueryFieldDescriptor $descriptor, FieldHandlerInterface $next): FieldDefinition|null
{
$resolver = $descriptor->getResolver();
return $next->handle($descriptor->withResolver(
static function (...$args) use ($resolver): mixed {
$value = $resolver(...$args);
return is_string($value) ? strtoupper($value) : $value;
},
));
}
}
#[Query]
#[Uppercase]
public function greeting(): string
{
return 'hello world'; // Returns "HELLO WORLD"
}
While the schema is built, field and input field directives run after the middlewares you registered
and after the #[Logged], #[Right] and #[Security] middlewares. If one of those hides the field,
the directive doesn't run.
At request time the order is reversed. Those middlewares enforce their checks by wrapping the
resolver, and a directive that wraps the resolver with withResolver() wraps theirs, so its wrapper
runs first. Code placed before the call to the wrapped resolver ($resolver(...$args) above) runs
before the #[Logged], #[Right] and #[Security] checks, even for a user who will be refused.
Code placed after the call only runs once the checks pass. On a field, it also runs when a check is
set to fail with a fallback value (#[FailWith], #[Security(failWith: ...)]), and receives that
value; input fields have no fallback, so a refused check throws before it. Keep side effects after the
call, or repeat the check yourself.
Changing a type
Type-level hooks receive the built webonyx type. Call $next and adjust what it returns:
#[Attribute(Attribute::TARGET_CLASS)]
final class Experimental implements BehavioralObjectTypeDirective
{
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(name: 'experimental', locations: [DirectiveLocation::OBJECT]);
}
public function applyToObjectType(ObjectTypeDescriptor $descriptor, ObjectTypeHandlerInterface $next): MutableObjectType
{
$type = $next->handle($descriptor);
$type->description = trim(($type->description ?? '') . "\n\nExperimental: may change without notice.");
return $type;
}
}
#[OneOf] is itself a BehavioralInputObjectTypeDirective that sets the isOneOf flag of the input
type: see TheCodingMachine\GraphQLite\Directives\BuiltIn\OneOf for a complete example.
A directive can be behavioral for one location and metadata-only for another: implement
BehavioralFieldDirective and InputFieldDirective, for instance.
Naming rules
- Directive names must be unique. Two classes declaring the same name throw an
InvalidDirectiveException. skip,includeandspecifiedByare reserved, even withbuiltIn: true: webonyx/graphql-php defines them only on locations GraphQLite cannot apply.deprecatedandoneOfare bound to GraphQLite's#[Deprecated]and#[OneOf]. To replace one of those bindings with your own class, declare the same name and setbuiltIn: trueon its definition:
#[Attribute(Attribute::TARGET_CLASS)]
final class MyOneOf implements BehavioralInputObjectTypeDirective
{
public static function definition(): DirectiveDefinition
{
return new DirectiveDefinition(
name: 'oneOf',
locations: [DirectiveLocation::INPUT_OBJECT],
builtIn: true,
);
}
public function applyToInputObjectType(InputObjectTypeDescriptor $descriptor, InputObjectTypeHandlerInterface $next): MutableInputObjectType
{
// ...
}
}
A builtIn: true directive reuses the definition that webonyx/graphql-php already declares, so its
name must be one webonyx defines, and its locations must be among the ones webonyx defines for it;
otherwise it throws an InvalidDirectiveException. Its arguments must match webonyx's as well.
Limitations
- Only the four locations above can be applied from PHP. Directives on arguments, enums, enum
values, interfaces, unions and scalars are not supported yet, and declaring one of those locations
throws an
InvalidDirectiveException. - Arguments are limited to
string,int,floatandbool. Enums, lists and input objects are not supported yet. - Executable directives (the ones clients put in their queries, such as
@skip) cannot be defined: declaring an executable location throws anInvalidDirectiveException.