2016-11-08 16:41:38 +03:00
<!DOCTYPE html>
<!-- [if IE 8]><html class="no - js lt - ie9" lang="en" > <![endif] -->
<!-- [if gt IE 8]><! --> < html class = "no-js" lang = "en" > <!-- <![endif] -->
< head >
< meta charset = "utf-8" >
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< link rel = "shortcut icon" href = "../img/favicon.ico" >
2017-04-25 14:15:40 +03:00
< title > Fetching Data - graphql-php< / title >
2016-11-08 16:41:38 +03:00
< link href = 'https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel = 'stylesheet' type = 'text/css' >
< link rel = "stylesheet" href = "../css/theme.css" type = "text/css" / >
< link rel = "stylesheet" href = "../css/theme_extra.css" type = "text/css" / >
< link rel = "stylesheet" href = "../css/highlight.css" >
< script >
// Current page data
var mkdocs_page_name = "Fetching Data";
var mkdocs_page_input_path = "data-fetching.md";
var mkdocs_page_url = "/data-fetching/";
< / script >
< script src = "../js/jquery-2.1.1.min.js" > < / script >
< script src = "../js/modernizr-2.8.3.min.js" > < / script >
2017-04-25 14:15:40 +03:00
< script type = "text/javascript" src = "../js/highlight.pack.js" > < / script >
2016-11-08 16:41:38 +03:00
< / head >
< body class = "wy-body-for-nav" role = "document" >
< div class = "wy-grid-for-nav" >
< nav data-toggle = "wy-nav-shift" class = "wy-nav-side stickynav" >
< div class = "wy-side-nav-search" >
< a href = ".." class = "icon icon-home" > graphql-php< / a >
< div role = "search" >
< form id = "rtd-search-form" class = "wy-form" action = "../search.html" method = "get" >
< input type = "text" name = "q" placeholder = "Search docs" / >
< / form >
< / div >
< / div >
< div class = "wy-menu wy-menu-vertical" data-spy = "affix" role = "navigation" aria-label = "main navigation" >
2017-04-25 14:15:40 +03:00
< ul class = "current" >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l1" >
< a class = "" href = ".." > About< / a >
< / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l1" >
< a class = "" href = "../getting-started/" > Getting Started< / a >
< / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l1" >
2017-08-20 19:28:59 +03:00
< a class = "" href = "../complementary-tools/" > Complementary Tools< / a >
< / li >
< li class = "toctree-l1" >
< span class = "caption-text" > Type Definitions< / span >
2017-04-25 14:15:40 +03:00
< ul class = "subnav" >
< li class = "" >
< a class = "" href = "../type-system/" > Introduction< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/object-types/" > Object Types< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/scalar-types/" > Scalar Types< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/enum-types/" > Enumeration Types< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/lists-and-nonnulls/" > Lists and Non-Null< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/interfaces/" > Interfaces< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/unions/" > Unions< / a >
< / li >
< li class = "" >
2017-08-20 19:28:59 +03:00
< a class = "" href = "../type-system/input-types/" > Mutations and Input Types< / a >
2017-04-25 14:15:40 +03:00
< / li >
< li class = "" >
< a class = "" href = "../type-system/directives/" > Directives< / a >
< / li >
< li class = "" >
< a class = "" href = "../type-system/schema/" > Schema< / a >
< / li >
2017-08-20 19:28:59 +03:00
< li class = "" >
< a class = "" href = "../type-system/type-language/" > Using Type Language< / a >
< / li >
2017-04-25 14:15:40 +03:00
< / ul >
< / li >
< li class = "toctree-l1" >
< a class = "" href = "../executing-queries/" > Executing Queries< / a >
< / li >
< li class = "toctree-l1 current" >
< a class = "current" href = "./" > Fetching Data< / a >
2016-11-08 16:41:38 +03:00
< ul class = "subnav" >
2017-04-25 14:15:40 +03:00
< li class = "toctree-l2" > < a href = "#overview" > Overview< / a > < / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l2" > < a href = "#default-field-resolver" > Default Field Resolver< / a > < / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l2" > < a href = "#default-field-resolver-per-type" > Default Field Resolver per Type< / a > < / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l2" > < a href = "#solving-n1-problem" > Solving N+1 Problem< / a > < / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l2" > < a href = "#async-php" > Async PHP< / a > < / li >
2016-11-08 16:41:38 +03:00
< / ul >
2017-04-25 14:15:40 +03:00
< / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l1" >
< a class = "" href = "../error-handling/" > Handling Errors< / a >
< / li >
2016-11-08 16:41:38 +03:00
2017-04-25 14:15:40 +03:00
< li class = "toctree-l1" >
2017-08-20 19:28:59 +03:00
< a class = "" href = "../security/" > Security< / a >
< / li >
< li class = "toctree-l1" >
< a class = "" href = "../how-it-works/" > How it works< / a >
< / li >
< li class = "toctree-l1" >
< a class = "" href = "../reference/" > Class Reference< / a >
2017-04-25 14:15:40 +03:00
< / li >
2016-11-08 16:41:38 +03:00
< / ul >
< / div >
< / nav >
< section data-toggle = "wy-nav-shift" class = "wy-nav-content-wrap" >
< nav class = "wy-nav-top" role = "navigation" aria-label = "top navigation" >
< i data-toggle = "wy-nav-top" class = "fa fa-bars" > < / i >
< a href = ".." > graphql-php< / a >
< / nav >
< div class = "wy-nav-content" >
< div class = "rst-content" >
< div role = "navigation" aria-label = "breadcrumbs navigation" >
< ul class = "wy-breadcrumbs" >
< li > < a href = ".." > Docs< / a > » < / li >
< li > Fetching Data< / li >
< li class = "wy-breadcrumbs-aside" >
< / li >
< / ul >
< hr / >
< / div >
< div role = "main" >
< div class = "section" >
2016-12-14 16:23:08 +03:00
< h1 id = "overview" > Overview< / h1 >
< p > GraphQL is data-storage agnostic. You can use any underlying data storage engine, including SQL or NoSQL database,
plain files or in-memory data structures.< / p >
2017-08-20 19:28:59 +03:00
< p > In order to convert the GraphQL query to PHP array, < strong > graphql-php< / strong > traverses query fields (using depth-first algorithm) and
runs special < strong > resolve< / strong > function on each field. This < strong > resolve< / strong > function is provided by you as a part of
< a href = "../type-system/object-types/#field-configuration-options" > field definition< / a > or < a href = "../executing-queries/#overview" > query execution call< / a > .< / p >
< p > Result returned by < strong > resolve< / strong > function is directly included in the response (for scalars and enums)
2016-12-14 16:23:08 +03:00
or passed down to nested fields (for objects).< / p >
< p > Let's walk through an example. Consider following GraphQL query:< / p >
< pre > < code class = "graphql" > {
lastStory {
title
author {
name
}
}
}
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > We need a Schema that can fulfill it. On the very top level the Schema contains Query type:< / p >
< pre > < code class = "php" > < ?php
use GraphQL\Type\Definition\ObjectType;
$queryType = new ObjectType([
2016-12-14 16:23:08 +03:00
'name' => 'Query',
'fields' => [
'lastStory' => [
'type' => $blogStoryType,
'resolve' => function() {
return [
'id' => 1,
'title' => 'Example blog post',
'authorId' => 1
];
}
]
]
]);
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > As we see field < strong > lastStory< / strong > has < strong > resolve< / strong > function that is responsible for fetching data.< / p >
< p > In our example, we simply return array value, but in the real-world application you would query
your database/cache/search index and return the result.< / p >
< p > Since < strong > lastStory< / strong > is of composite type < strong > BlogStory< / strong > this result is passed down to fields of this type:< / p >
< pre > < code class = "php" > < ?php
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
$blogStoryType = new ObjectType([
2016-12-14 16:23:08 +03:00
'name' => 'BlogStory',
'fields' => [
'author' => [
'type' => $userType,
'resolve' => function($blogStory) {
$users = [
1 => [
'id' => 1,
'name' => 'Smith'
],
2 => [
'id' => 2,
'name' => 'Anderson'
]
];
return $users[$blogStory['authorId']];
}
],
'title' => [
'type' => Type::string()
]
]
]);
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > Here < strong > $blogStory< / strong > is the array returned by < strong > lastStory< / strong > field above. < / p >
< p > Again: in the real-world applications you would fetch user data from data store by < strong > authorId< / strong > and return it.
Also, note that you don't have to return arrays. You can return any value, < strong > graphql-php< / strong > will pass it untouched
2016-12-14 16:23:08 +03:00
to nested resolvers.< / p >
2017-08-20 19:28:59 +03:00
< p > But then the question appears - field < strong > title< / strong > has no < strong > resolve< / strong > option. How is it resolved?< / p >
< p > There is a default resolver for all fields. When you define your own < strong > resolve< / strong > function
2016-12-14 16:23:08 +03:00
for a field you simply override this default resolver.< / p >
< h1 id = "default-field-resolver" > Default Field Resolver< / h1 >
< p > < strong > graphql-php< / strong > provides following default field resolver:< / p >
2017-08-20 19:28:59 +03:00
< pre > < code class = "php" > < ?php
function defaultFieldResolver($source, $args, $context, \GraphQL\Type\Definition\ResolveInfo $info)
2016-12-14 16:23:08 +03:00
{
$fieldName = $info-> fieldName;
$property = null;
if (is_array($source) || $source instanceof \ArrayAccess) {
if (isset($source[$fieldName])) {
$property = $source[$fieldName];
}
} else if (is_object($source)) {
if (isset($source-> {$fieldName})) {
$property = $source-> {$fieldName};
}
}
return $property instanceof \Closure ? $property($source, $args, $context) : $property;
}
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > As you see it returns value by key (for arrays) or property (for objects).
If the value is not set - it returns < strong > null< / strong > .< / p >
< p > To override the default resolver, pass it as an argument of < a href = "../executing-queries/" > executeQuery< / a > call.< / p >
2016-12-14 16:23:08 +03:00
< h1 id = "default-field-resolver-per-type" > Default Field Resolver per Type< / h1 >
< p > Sometimes it might be convenient to set default field resolver per type. You can do so by providing
< a href = "../type-system/object-types/#configuration-options" > resolveField option in type config< / a > . For example:< / p >
2017-08-20 19:28:59 +03:00
< pre > < code class = "php" > < ?php
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
$userType = new ObjectType([
2016-12-14 16:23:08 +03:00
'name' => 'User',
'fields' => [
'name' => Type::string(),
'email' => Type::string()
],
'resolveField' => function(User $user, $args, $context, ResolveInfo $info) {
switch ($info-> fieldName) {
case 'name':
return $user-> getName();
case 'email':
return $user-> getEmail();
default:
return null;
}
}
]);
< / code > < / pre >
< p > Keep in mind that < strong > field resolver< / strong > has precedence over < strong > default field resolver per type< / strong > which in turn
has precedence over < strong > default field resolver< / strong > .< / p >
< h1 id = "solving-n1-problem" > Solving N+1 Problem< / h1 >
2016-12-17 01:21:05 +03:00
< p > Since: 0.9.0< / p >
2017-08-20 19:28:59 +03:00
< p > One of the most annoying problems with data fetching is a so-called
< a href = "https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/" > N+1 problem< / a > . < br >
Consider following GraphQL query:< / p >
2016-12-14 16:23:08 +03:00
< pre > < code > {
topStories(limit: 10) {
title
author {
name
email
}
}
}
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > Naive field resolution process would require up to 10 calls to the underlying data store to fetch authors for all 10 stories.< / p >
< p > < strong > graphql-php< / strong > provides tools to mitigate this problem: it allows you to defer actual field resolution to a later stage
2016-12-14 16:23:08 +03:00
when one batched query could be executed instead of 10 distinct queries.< / p >
2017-08-20 19:28:59 +03:00
< p > Here is an example of < strong > BlogStory< / strong > resolver for field < strong > author< / strong > that uses deferring:< / p >
< pre > < code class = "php" > < ?php
'resolve' => function($blogStory) {
2016-12-14 16:23:08 +03:00
MyUserBuffer::add($blogStory['authorId']);
return new GraphQL\Deferred(function () use ($blogStory) {
2016-12-17 01:21:05 +03:00
MyUserBuffer::loadBuffered();
2016-12-14 16:23:08 +03:00
return MyUserBuffer::get($blogStory['authorId']);
});
}
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > In this example, we fill up the buffer with 10 author ids first. Then < strong > graphql-php< / strong > continues
2016-12-14 16:23:08 +03:00
resolving other non-deferred fields until there are none of them left.< / p >
2017-08-20 19:28:59 +03:00
< p > After that, it calls closures wrapped by < code > GraphQL\Deferred< / code > which in turn load all buffered
ids once (using SQL IN(?), Redis MGET or other similar tools) and returns final field value.< / p >
2016-12-14 16:23:08 +03:00
< p > Originally this approach was advocated by Facebook in their < a href = "https://github.com/facebook/dataloader" > Dataloader< / a >
2017-08-20 19:28:59 +03:00
project. This solution enables very interesting optimizations at no cost. Consider the following query:< / p >
< pre > < code class = "graphql" > {
2016-12-14 16:23:08 +03:00
topStories(limit: 10) {
author {
email
}
}
category {
stories(limit: 10) {
author {
email
}
}
}
}
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > Even though < strong > author< / strong > field is located on different levels of the query - it can be buffered in the same buffer.
In this example, only one query will be executed for all story authors comparing to 20 queries
in a naive implementation.< / p >
2016-12-14 16:23:08 +03:00
< h1 id = "async-php" > Async PHP< / h1 >
2017-08-20 19:28:59 +03:00
< p > Since: 0.10.0 (version 0.9.0 had slightly different API which still works, but is deprecated)< / p >
< p > If your project runs in an environment that supports async operations
(like HHVM, ReactPHP, Icicle.io, appserver.io, PHP threads, etc)
you can leverage the power of your platform to resolve some fields asynchronously.< / p >
2016-12-14 16:23:08 +03:00
< p > The only requirement: your platform must support the concept of Promises compatible with
< a href = "https://promisesaplus.com/" > Promises A+< / a > specification.< / p >
2017-08-20 19:28:59 +03:00
< p > To start using this feature, switch facade method for query execution from
< strong > executeQuery< / strong > to < strong > promiseToExecute< / strong > :< / p >
< pre > < code class = "php" > < ?php
use GraphQL\GraphQL;
use GraphQL\Executor\ExecutionResult;
$promise = GraphQL::promiseToExecute(
$promiseAdapter,
$schema,
$queryString,
$rootValue = null,
$contextValue = null,
$variableValues = null,
$operationName = null,
$fieldResolver = null,
$validationRules = null
);
$promise-> then(function(ExecutionResult $result) {
return $result-> toArray();
});
2016-12-14 16:23:08 +03:00
< / code > < / pre >
2017-08-20 19:28:59 +03:00
< p > Where < strong > $promiseAdapter< / strong > is an instance of:< / p >
2016-12-14 16:23:08 +03:00
< ul >
2017-08-20 19:28:59 +03:00
< li >
< p > For < a href = "https://github.com/reactphp/react" > ReactPHP< / a > (requires < strong > react/promise< / strong > as composer dependency): < br >
< code > GraphQL\Executor\Promise\Adapter\ReactPromiseAdapter< / code > < / p >
< / li >
< li >
< p > Other platforms: write your own class implementing interface: < br >
< a href = "../reference/#graphqlexecutorpromisepromiseadapter" > < code > GraphQL\Executor\Promise\PromiseAdapter< / code > < / a > . < / p >
< / li >
2016-12-14 16:23:08 +03:00
< / ul >
2017-08-20 19:28:59 +03:00
< p > Then your < strong > resolve< / strong > functions should return promises of your platform instead of < code > GraphQL\Deferred< / code > s.< / p >
2016-11-08 16:41:38 +03:00
< / div >
< / div >
< footer >
< div class = "rst-footer-buttons" role = "navigation" aria-label = "footer navigation" >
2016-12-14 16:23:08 +03:00
< a href = "../error-handling/" class = "btn btn-neutral float-right" title = "Handling Errors" > Next < span class = "icon icon-circle-arrow-right" > < / span > < / a >
2016-11-08 16:41:38 +03:00
2016-12-14 16:23:08 +03:00
< a href = "../executing-queries/" class = "btn btn-neutral" title = "Executing Queries" > < span class = "icon icon-circle-arrow-left" > < / span > Previous< / a >
2016-11-08 16:41:38 +03:00
< / div >
< hr / >
< div role = "contentinfo" >
<!-- Copyright etc -->
< / div >
Built with < a href = "http://www.mkdocs.org" > MkDocs< / a > using a < a href = "https://github.com/snide/sphinx_rtd_theme" > theme< / a > provided by < a href = "https://readthedocs.org" > Read the Docs< / a > .
< / footer >
< / div >
< / div >
< / section >
2017-04-25 14:15:40 +03:00
2016-11-08 16:41:38 +03:00
< / div >
2017-04-25 14:15:40 +03:00
< div class = "rst-versions" role = "note" style = "cursor: pointer" >
2016-11-08 16:41:38 +03:00
< span class = "rst-current-version" data-toggle = "rst-current-version" >
2016-12-14 16:23:08 +03:00
< span > < a href = "../executing-queries/" style = "color: #fcfcfc;" > « Previous< / a > < / span >
2016-11-08 16:41:38 +03:00
2016-12-14 16:23:08 +03:00
< span style = "margin-left: 15px" > < a href = "../error-handling/" style = "color: #fcfcfc" > Next » < / a > < / span >
2016-11-08 16:41:38 +03:00
< / span >
< / div >
2017-04-25 14:15:40 +03:00
< script src = "../js/theme.js" > < / script >
2016-11-08 16:41:38 +03:00
< / body >
< / html >