{"id":14975975,"url":"https://github.com/mghoneimy/php-graphql-client","last_synced_at":"2025-05-15T15:02:11.176Z","repository":{"id":38848297,"uuid":"151942785","full_name":"mghoneimy/php-graphql-client","owner":"mghoneimy","description":"A PHP library that simplifies the process of interacting with GraphQL API's by providing simple client and query generator classes.","archived":false,"fork":false,"pushed_at":"2024-04-01T13:39:12.000Z","size":350,"stargazers_count":302,"open_issues_count":23,"forks_count":87,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-10-29T17:14:21.483Z","etag":null,"topics":["graphql-api","graphql-client","php","php-library","query-builder"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mghoneimy.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-07T13:11:48.000Z","updated_at":"2024-10-23T08:31:08.000Z","dependencies_parsed_at":"2024-06-18T11:14:24.264Z","dependency_job_id":null,"html_url":"https://github.com/mghoneimy/php-graphql-client","commit_stats":{"total_commits":182,"total_committers":15,"mean_commits":"12.133333333333333","dds":"0.10439560439560436","last_synced_commit":"caadeba3e8af0d3d5cf6481e393cf933f3a83f3c"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mghoneimy%2Fphp-graphql-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mghoneimy%2Fphp-graphql-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mghoneimy%2Fphp-graphql-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mghoneimy%2Fphp-graphql-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mghoneimy","download_url":"https://codeload.github.com/mghoneimy/php-graphql-client/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254364268,"owners_count":22058877,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graphql-api","graphql-client","php","php-library","query-builder"],"created_at":"2024-09-24T13:53:03.384Z","updated_at":"2025-05-15T15:02:11.052Z","avatar_url":"https://github.com/mghoneimy.png","language":"PHP","readme":"# PHP GraphQL Client\n![Build Status](https://github.com/mghoneimy/php-graphql-client/actions/workflows/php.yml/badge.svg)\n[![Total\nDownloads](https://poser.pugx.org/gmostafa/php-graphql-client/downloads)](https://packagist.org/packages/gmostafa/php-graphql-client)\n[![Latest Stable\nVersion](https://poser.pugx.org/gmostafa/php-graphql-client/v/stable)](https://packagist.org/packages/gmostafa/php-graphql-client)\n[![License](https://poser.pugx.org/gmostafa/php-graphql-client/license)](https://packagist.org/packages/gmostafa/php-graphql-client)\n\nA GraphQL client written in PHP which provides very simple, yet powerful, query\ngenerator classes that make the process of interacting with a GraphQL server a\nvery simple one.\n\n# Usage\n\nThere are 3 primary ways to use this package to generate your GraphQL queries:\n\n1. Query Class: Simple class that maps to GraphQL queries. It's designed to\n   manipulate queries with ease and speed.\n2. QueryBuilder Class: Builder class that can be used to generate `Query`\n   objects dynamically. It's design to be used in cases where a query is being\n   build in a dynamic fashion.\n3. PHP GraphQL-OQM: An extension to this package. It Eliminates the need to\n   write any GraphQL queries or refer to the API documentation or syntax. It\n   generates query objects from the API schema, declaration exposed through\n   GraphQL's introspection, which can then be simply interacted with.\n\n# Installation\n\nRun the following command to install the package using composer:\n\n```\n$ composer require gmostafa/php-graphql-client\n```\n\n# Object-to-Query-Mapper Extension\n\nTo avoid the hassle of having to write _any_ queries and just interact with PHP\nobjects generated from your API schema visit [PHP GraphQL OQM repository](\nhttps://github.com/mghoneimy/php-graphql-oqm)\n\n# Query Examples\n\n## Simple Query\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThis simple query will retrieve all companies displaying their names and serial\nnumbers.\n\n### The Full Form\n\nThe query provided in the previous example is represented in the\n\"shorthand form\". The shorthand form involves writing a reduced number of code\nlines which speeds up the process of wriing querries. Below is an example of\nthe full form for the exact same query written in the previous example.\n\n```php\n$gql = (new Query())\n    -\u003esetSelectionSet(\n        [\n            (new Query('companies'))\n                -\u003esetSelectionSet(\n                    [\n                        'name',\n                        'serialNumber'\n                    ]\n                )\n        ]\n    );\n```\n\nAs seen in the example, the shorthand form is simpler to read and write, it's\ngenerally preferred to use compared to the full form.\n\nThe full form shouldn't be used unless the query can't be represented in the\nshorthand form, which has only one case, when we want to run multiple queries\nin the same object.\n\n\n## Multiple Queries\n```php\n$gql = (new Query())\n    -\u003esetSelectionSet(\n        [\n            (new Query('companies'))\n            -\u003esetSelectionSet(\n                [\n                    'name',\n                    'serialNumber'\n                ]\n            ),\n            (new Query('countries'))\n            -\u003esetSelectionSet(\n                [\n                    'name',\n                    'code',\n                ]\n            )\n        ]\n    );\n```\n\nThis query retrieves all companies and countries displaying some data fields\nfor each. It basically runs two (or more if needed) independent queries in\none query object envelop.\n\nWriting multiple queries requires writing the query object in the full form\nto represent each query as a subfield under the parent query object.\n\n## Nested Queries\n```php\n$gql = (new Query('companies'))\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber',\n            (new Query('branches'))\n                -\u003esetSelectionSet(\n                    [\n                        'address',\n                        (new Query('contracts'))\n                            -\u003esetSelectionSet(['date'])\n                    ]\n                )\n        ]\n    );\n```\n\nThis query is a more complex one, retrieving not just scalar fields, but object\nfields as well. This query returns all companies, displaying their names, serial\nnumbers, and for each company, all its branches, displaying the branch address,\nand for each address, it retrieves all contracts bound to this address,\ndisplaying their dates.\n\n## Query With Arguments\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetArguments(['name' =\u003e 'Tech Co.', 'first' =\u003e 3])\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThis query does not retrieve all companies by adding arguments. This query will\nretrieve the first 3 companies with the name \"Tech Co.\", displaying their names\nand serial numbers.\n\n## Query With Array Argument\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetArguments(['serialNumbers' =\u003e [159, 260, 371]])\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThis query is a special case of the arguments query. In this example, the query\nwill retrieve only the companies with serial number in one of 159, 260, and 371,\ndisplaying the name and serial number.\n\n## Query With Input Object Argument\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetArguments(['filter' =\u003e new RawObject('{name_starts_with: \"Face\"}')])\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThis query is another special case of the arguments query. In this example,\nwe're setting a custom input object \"filter\" with some values to limit the\ncompanies being returned. We're setting the filter \"name_starts_with\" with\nvalue \"Face\".  This query will retrieve only the companies whose names\nstart with the phrase \"Face\".\n\nThe RawObject class being constructed is used for injecting the string into the\nquery as it is. Whatever string is input into the RawObject constructor will be\nput in the query as it is without any custom formatting normally done by the\nquery class.\n\n## Query With Variables\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetVariables(\n        [\n            new Variable('name', 'String', true),\n            new Variable('limit', 'Int', false, 5)\n        ]\n    )\n    -\u003esetArguments(['name' =\u003e '$name', 'first' =\u003e '$limit'])\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThis query shows how variables can be used in this package to allow for dynamic\nrequests enabled by GraphQL standards.\n\n### The Variable Class\n\nThe Variable class is an immutable class that represents a variable in GraphQL\nstandards. Its constructor receives 4 arguments:\n\n- name: Represents the variable name\n- type: Represents the variable type according to the GraphQL server schema\n- isRequired (Optional): Represents if the variable is required or not, it's\nfalse by default\n- defaultValue (Optional): Represents the default value to be assigned to the\nvariable. The default value will only be considered\nif the isRequired argument is set to false.\n\n## Using an alias\n```php\n$gql = (new Query())\n    -\u003esetSelectionSet(\n        [\n            (new Query('companies', 'TechCo'))\n                -\u003esetArguments(['name' =\u003e 'Tech Co.'])\n                -\u003esetSelectionSet(\n                    [\n                        'name',\n                        'serialNumber'\n                    ]\n                ),\n            (new Query('companies', 'AnotherTechCo'))\n                -\u003esetArguments(['name' =\u003e 'A.N. Other Tech Co.'])\n                -\u003esetSelectionSet(\n                    [\n                        'name',\n                        'serialNumber'\n                    ]\n                )\n        ]\n    );\n```\n\nAn alias can be set in the second argument of the Query constructor for occasions when the same object needs to be retrieved multiple times with different arguments.\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetAlias('CompanyAlias')\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n```\n\nThe alias can also be set via the setter method.\n\n## Using Interfaces: Query With Inline Fragments\n\nWhen querying a field that returns an interface type, you might need to use\ninline fragments to access data on the underlying concrete type.\n\nThis example show how to generate inline fragments using this package:\n\n```php\n$gql = new Query('companies');\n$gql-\u003esetSelectionSet(\n    [\n        'serialNumber',\n        'name',\n        (new InlineFragment('PrivateCompany'))\n            -\u003esetSelectionSet(\n                [\n                    'boardMembers',\n                    'shareholders',\n                ]\n            ),\n    ]\n);\n```\n\n# The Query Builder\n\nThe QueryBuilder class can be used to construct Query objects dynamically, which\ncan be useful in some cases. It works very similarly to the Query class, but the\nQuery building is divided into steps.\n\nThat's how the \"Query With Input Object Argument\" example can be created using\nthe QueryBuilder:\n\n```php\n$builder = (new QueryBuilder('companies'))\n    -\u003esetVariable('namePrefix', 'String', true)\n    -\u003esetArgument('filter', new RawObject('{name_starts_with: $namePrefix}'))\n    -\u003eselectField('name')\n    -\u003eselectField('serialNumber');\n$gql = $builder-\u003egetQuery();\n```\n\nAs with the Query class, an alias can be set using the second constructor argument.\n\n```php\n$builder = (new QueryBuilder('companies', 'CompanyAlias'))\n    -\u003eselectField('name')\n    -\u003eselectField('serialNumber');\n\n$gql = $builder-\u003egetQuery();\n```\n\nOr via the setter method\n\n```php\n$builder = (new QueryBuilder('companies'))\n    -\u003esetAlias('CompanyAlias')\n    -\u003eselectField('name')\n    -\u003eselectField('serialNumber');\n\n$gql = $builder-\u003egetQuery();\n```\n\n### The Full Form\n\nJust like the Query class, the QueryBuilder class can be written in full form to\nenable writing multiple queries under one query builder object. Below is an\nexample for how the full form can be used with the QueryBuilder:\n\n```php\n$builder = (new QueryBuilder())\n    -\u003esetVariable('namePrefix', 'String', true)\n    -\u003eselectField(\n        (new QueryBuilder('companies'))\n            -\u003esetArgument('filter', new RawObject('{name_starts_with: $namePrefix}'))\n            -\u003eselectField('name')\n            -\u003eselectField('serialNumber')\n    )\n    -\u003eselectField(\n        (new QueryBuilder('company'))\n            -\u003esetArgument('serialNumber', 123)\n            -\u003eselectField('name')\n    );\n$gql = $builder-\u003egetQuery();\n```\n\nThis query is an extension to the query in the previous example. It returns all\ncompanies starting with a name prefix and returns the company with the\n`serialNumber` of value 123, both in the same response.\n\n# Constructing The Client\n\nA Client object can easily be instantiated by providing the GraphQL endpoint\nURL. \n\nThe Client constructor also receives an optional \"authorizationHeaders\"\narray, which can be used to add authorization headers to all requests being sent\nto the GraphQL server.\n\nExample:\n\n```php\n$client = new Client(\n    'http://api.graphql.com',\n    ['Authorization' =\u003e 'Basic xyz']\n);\n```\n\n\nThe Client constructor also receives an optional \"httpOptions\" array, which\n**overrides** the \"authorizationHeaders\" and can be used to add custom\n[Guzzle HTTP Client request options](https://guzzle.readthedocs.io/en/latest/request-options.html).\n\nExample:\n\n```php\n$client = new Client(\n    'http://api.graphql.com',\n    [],\n    [ \n        'connect_timeout' =\u003e 5,\n        'timeout' =\u003e 5,\n        'headers' =\u003e [\n            'Authorization' =\u003e 'Basic xyz'\n            'User-Agent' =\u003e 'testing/1.0',\n        ],\n        'proxy' =\u003e [\n                'http'  =\u003e 'tcp://localhost:8125', // Use this proxy with \"http\"\n                'https' =\u003e 'tcp://localhost:9124', // Use this proxy with \"https\",\n                'no' =\u003e ['.mit.edu', 'foo.com']    // Don't use a proxy with these\n        ],\n        'cert' =\u003e ['/path/server.pem', 'password']\n        ...\n    ]\n);\n```\n\n\nIt is possible to use your own preconfigured HTTP client that implements the [PSR-18 interface](https://www.php-fig.org/psr/psr-18/).\n\nExample:\n\n```php\n$client = new Client(\n    'http://api.graphql.com',\n    [],\n    [],\n    $myHttpClient\n);\n```\n\n# Running Queries\n\n## Result Formatting\n\nRunning query with the GraphQL client and getting the results in object\nstructure:\n\n```php\n$results = $client-\u003erunQuery($gql);\n$results-\u003egetData()-\u003ecompanies[0]-\u003ebranches;\n```\nOr getting results in array structure:\n\n```php\n$results = $client-\u003erunQuery($gql, true);\n$results-\u003egetData()['companies'][1]['branches']['address'];\n```\n\n## Passing Variables to Queries\n\nRunning queries containing variables requires passing an associative array which\nmaps variable names (keys) to variable values (values) to the `runQuery` method.\nHere's an example:\n\n```php\n$gql = (new Query('companies'))\n    -\u003esetVariables(\n        [\n            new Variable('name', 'String', true),\n            new Variable('limit', 'Int', false, 5)\n        ]\n    )\n    -\u003esetArguments(['name' =\u003e '$name', 'first' =\u003e '$limit'])\n    -\u003esetSelectionSet(\n        [\n            'name',\n            'serialNumber'\n        ]\n    );\n$variablesArray = ['name' =\u003e 'Tech Co.', 'first' =\u003e 5];\n$results = $client-\u003erunQuery($gql, true, $variablesArray);\n```\n\n# Mutations\n\nMutations follow the same rules of queries in GraphQL, they select fields on\nreturned objects, receive arguments, and can have sub-fields.\n\nHere's a sample example on how to construct and run mutations:\n\n```php\n$mutation = (new Mutation('createCompany'))\n    -\u003esetArguments(['companyObject' =\u003e new RawObject('{name: \"Trial Company\", employees: 200}')])\n    -\u003esetSelectionSet(\n        [\n            '_id',\n            'name',\n            'serialNumber',\n        ]\n    );\n$results = $client-\u003erunQuery($mutation);\n```\n\nMutations can be run by the client the same way queries are run.\n\n## Mutations With Variables Example\n\nMutations can utilize the variables in the same way Queries can. Here's an\nexample on how to use the variables to pass input objects to the GraphQL server\ndynamically:\n\n```php\n$mutation = (new Mutation('createCompany'))\n    -\u003esetVariables([new Variable('company', 'CompanyInputObject', true)])\n    -\u003esetArguments(['companyObject' =\u003e '$company']);\n\n$variables = ['company' =\u003e ['name' =\u003e 'Tech Company', 'type' =\u003e 'Testing', 'size' =\u003e 'Medium']];\n$client-\u003erunQuery(\n    $mutation, true, $variables\n);\n```\n\nThese are the resulting mutation and the variables passed with it:\n\n```php\nmutation($company: CompanyInputObject!) {\n  createCompany(companyObject: $company)\n}\n{\"company\":{\"name\":\"Tech Company\",\"type\":\"Testing\",\"size\":\"Medium\"}}\n```\n\n# Live API Example\n\nGraphQL Pokemon is a very cool public GraphQL API available to retrieve Pokemon\ndata. The API is available publicly on the web, we'll use it to demo the\ncapabilities of this client.\n\nGithub Repo link: https://github.com/lucasbento/graphql-pokemon\n\nAPI link: https://graphql-pokemon.now.sh/\n\nThis query retrieves any pokemon's evolutions and their attacks:\n\n```php\nquery($name: String!) {\n  pokemon(name: $name) {\n    id\n    number\n    name\n    evolutions {\n      id\n      number\n      name\n      weight {\n        minimum\n        maximum\n      }\n      attacks {\n        fast {\n          name\n          type\n          damage\n        }\n      }\n    }\n  }\n}\n\n```\n\nThat's how this query can be written using the query class and run using the\nclient:\n\n```php\n$client = new Client(\n    'https://graphql-pokemon.now.sh/'\n);\n$gql = (new Query('pokemon'))\n    -\u003esetVariables([new Variable('name', 'String', true)])\n    -\u003esetArguments(['name' =\u003e '$name'])\n    -\u003esetSelectionSet(\n        [\n            'id',\n            'number',\n            'name',\n            (new Query('evolutions'))\n                -\u003esetSelectionSet(\n                    [\n                        'id',\n                        'number',\n                        'name',\n                        (new Query('attacks'))\n                            -\u003esetSelectionSet(\n                                [\n                                    (new Query('fast'))\n                                        -\u003esetSelectionSet(\n                                            [\n                                                'name',\n                                                'type',\n                                                'damage',\n                                            ]\n                                        )\n                                ]\n                            )\n                    ]\n                )\n        ]\n    );\ntry {\n    $name = readline('Enter pokemon name: ');\n    $results = $client-\u003erunQuery($gql, true, ['name' =\u003e $name]);\n}\ncatch (QueryError $exception) {\n    print_r($exception-\u003egetErrorDetails());\n    exit;\n}\nprint_r($results-\u003egetData()['pokemon']);\n```\n\nOr alternatively, That's how this query can be generated using the QueryBuilder\nclass:\n\n```php\n$client = new Client(\n    'https://graphql-pokemon.now.sh/'\n);\n$builder = (new QueryBuilder('pokemon'))\n    -\u003esetVariable('name', 'String', true)\n    -\u003esetArgument('name', '$name')\n    -\u003eselectField('id')\n    -\u003eselectField('number')\n    -\u003eselectField('name')\n    -\u003eselectField(\n        (new QueryBuilder('evolutions'))\n            -\u003eselectField('id')\n            -\u003eselectField('name')\n            -\u003eselectField('number')\n            -\u003eselectField(\n                (new QueryBuilder('attacks'))\n                    -\u003eselectField(\n                        (new QueryBuilder('fast'))\n                            -\u003eselectField('name')\n                            -\u003eselectField('type')\n                            -\u003eselectField('damage')\n                    )\n            )\n    );\ntry {\n    $name = readline('Enter pokemon name: ');\n    $results = $client-\u003erunQuery($builder, true, ['name' =\u003e $name]);\n}\ncatch (QueryError $exception) {\n    print_r($exception-\u003egetErrorDetails());\n    exit;\n}\nprint_r($results-\u003egetData()['pokemon']);\n```\n\n# Running Raw Queries\n\nAlthough not the primary goal of this package, but it supports running raw\nstring queries, just like any other client using the `runRawQuery` method in the\n`Client` class. Here's an example on how to use it:\n\n```php\n$gql = \u003c\u003c\u003cQUERY\nquery {\n    pokemon(name: \"Pikachu\") {\n        id\n        number\n        name\n        attacks {\n            special {\n                name\n                type\n                damage\n            }\n        }\n    }\n}\nQUERY;\n\n$results = $client-\u003erunRawQuery($gql);\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmghoneimy%2Fphp-graphql-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmghoneimy%2Fphp-graphql-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmghoneimy%2Fphp-graphql-client/lists"}