Skip to content

Introduce TypeReference that allows linking types together without having to pass a reference to the actual type object or use callbacks #1149

Open
@ruudk

Description

@ruudk

When specifying a field type, I have to either provide the actual object instance, or use a callback that delegates the call to a registry to fetch the single instance of that type.

$filters = new InputObjectType([
    'name' => 'StoryFiltersInput',
    'fields' => [
        'tags' => [
            'type' => fn() => Type::nonNull( Type::listOf( $registry->get(SomeOtherType::class) ) ),
        ]
    ]
]);

I wonder why it works like that. Maybe this is for legacy reasons. But I would find it way easier if I could just link types by a FQCN or GraphQL type name.

So what if we create something like this:

final class TypeReference extends GraphQLType
{
    public function __construct(public readonly string $name)
    {
    }

    public function toString() : string
    {
        return $this->name;
    }
}
$filters = new InputObjectType([
    'name' => 'StoryFiltersInput',
    'fields' => [
        'tags' => [
            'type' => Type::nonNull( Type::listOf( new TypeReference(SomeOtherType::class) ) ),
        ]
    ]
]);

Now the type can be added to the schema. As soon as the type is needed, it needs to resolve the TypeReference to the actual type.
But that only happens when it is needed.

From an API perspective, it feels so much nicer to define things like this than to go with the callbacks + registry approach.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions