graphql-php icon indicating copy to clipboard operation
graphql-php copied to clipboard

Using fragments

Open AhmadAudeh opened this issue 10 years ago • 4 comments

Its not clear how implement fragment in php code ?? Any example for that ??

AhmadAudeh avatar Dec 15 '15 08:12 AhmadAudeh

Fragments are part of GraphQL syntax (it's like sub-select in SQL). You don't write them in PHP. You write them in GraphQL language.

This library will parse your GraphQL query and match it against type system that you express with this library to produce final result.

Perhaps if you provide concrete example of what you're trying to achieve I could explain it better.

vladar avatar Dec 15 '15 11:12 vladar

thanks for the replay, For example if I have the following class witch represent a user type, then how could I create a fragment that includes the id and username fields ?

class UserType extends GraphQLType {
    protected $attributes = [
        'name' => 'User',
        'description' => 'A user'
    ];

    public function fields()
    {
        return [
            'id' => [
                'type' => Type::nonNull(Type::string()),
                'description' => 'The id of the user'
            ],
            'username' => [
                'type' => Type::string(),
                'description' => 'The email of user'
            ], 
             'count' => [
                'type' => Type::int(),
                'description' => 'count of the users'
            ],
            'friends' => [
                'type'=> function () {
                    return Type::listOf(GraphQL::type('user'));
                },
                'description' => 'frinds information'
            ]
        ];
    }
 protected function resolvefriendsField($root, $args)
    {
        // resolve code 
    }
}

Because right now my query is like :

FetchUsers{users(id:"2"){id,username}}

and I want it to be something like :

FetchUsers{users(id:"2"){...UserFragment}}

AhmadAudeh avatar Dec 15 '15 12:12 AhmadAudeh

This question is related to GraphQL language syntax in general. Check http://graphql.org/docs/queries/ for details.

Back to your question. Your Query should look like this:

query FetchUsers {
  users(id:"2") {...UserFragment}
}

fragment UserFragment on User {
  id
  username
}

vladar avatar Dec 15 '15 12:12 vladar

:+1: Ok, thanks :)

AhmadAudeh avatar Dec 15 '15 12:12 AhmadAudeh