PHP code example of overblog / dataloader-php

1. Go to this page and download the library: Download overblog/dataloader-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

overblog / dataloader-php example snippets


use Overblog\DataLoader\DataLoader;

$myBatchGetUsers = function ($keys) { /* ... */ };
$promiseAdapter = new MyPromiseAdapter();

$userLoader = new DataLoader($myBatchGetUsers, $promiseAdapter);

$userLoader->load(1)
  ->then(function ($user) use ($userLoader) { return $userLoader->load($user->invitedByID); })
  ->then(function ($invitedBy) { echo "User 1 was invited by $invitedBy"; });

// Elsewhere in your application
$userLoader->load(2)
  ->then(function ($user) use ($userLoader) { return $userLoader->load($user->invitedByID); })
  ->then(function ($invitedBy) { echo "User 2 was invited by $invitedBy"; });

// Synchronously waits on the promise to complete, if not using EventLoop.
$userLoader->await(); // or `DataLoader::await()`

[
  ['id' => 9, 'name' => 'Chicago'],
  ['id' => 1, 'name' => 'New York'],
  ['id' => 2, 'name' => 'San Francisco']  
]

[
  ['id' => 2, 'name' => 'San Francisco'],
  ['id' => 9, 'name' => 'Chicago'],
  null,
  ['id' => 1, 'name' => 'New York']
]

$userLoader =  new DataLoader(...);
$promise1A = $userLoader->load(1);
$promise1B = $userLoader->load(1);
var_dump($promise1A === $promise1B); // bool(true)

use Overblog\DataLoader\DataLoader;

// Request begins...
$userLoader = new DataLoader(...);

// And a value happens to be loaded (and cached).
$userLoader->load(4)->then(...);

// A mutation occurs, invalidating what might be in cache.
$sql = 'UPDATE users WHERE id=4 SET username="zuck"';
if (true === $conn->query($sql)) {
  $userLoader->clear(4);
}

// Later the value load is loaded again so the mutated data appears.
$userLoader->load(4)->then(...);

// Request completes.

$userLoader->load(1)->then(null, function ($exception) {
  if (/* determine if error is transient */) {
    $userLoader->clear(1);
  }
  throw $exception;
});

$myLoader = new DataLoader(function ($keys) {
  echo json_encode($keys);
  return someBatchLoadFn($keys);
}, $promiseAdapter, new Option(['cache' => false ]));

$myLoader->load('A');
$myLoader->load('B');
$myLoader->load('A');

// [ 'A', 'B', 'A' ]

$myLoader = new DataLoader(function($keys) use ($identityLoader) {
  $identityLoader->clearAll();
  return someBatchLoadFn($keys);
}, $promiseAdapter);

list($a, $b) = DataLoader::await($myLoader->loadMany(['a', 'b']));

list($a, $b) = DataLoader::await(\React\Promise\all([
  $myLoader->load('a'),
  $myLoader->load('b')
]));


use GraphQL\GraphQL;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use Overblog\DataLoader\DataLoader;
use Overblog\DataLoader\Promise\Adapter\Webonyx\GraphQL\SyncPromiseAdapter;
use Overblog\PromiseAdapter\Adapter\WebonyxGraphQLSyncPromiseAdapter;

/**
* @var \PDO $dbh
*/
// ...

$graphQLPromiseAdapter = new SyncPromiseAdapter();
$dataLoaderPromiseAdapter = new WebonyxGraphQLSyncPromiseAdapter($graphQLPromiseAdapter);
$userLoader = new DataLoader(function ($keys) { /*...*/ }, $dataLoaderPromiseAdapter);

GraphQL::setPromiseAdapter($graphQLPromiseAdapter);

$userType = new ObjectType([
  'name' => 'User',
  'fields' => function () use (&$userType, $userLoader, $dbh) {
     return [
            'name' => ['type' => Type::string()],
            'bestFriend' => [
                'type' => $userType,
                'resolve' => function ($user) use ($userLoader) {
                    $userLoader->load($user['bestFriendID']);
                }
            ],
            'friends' => [
                'args' => [
                    'first' => ['type' => Type::int() ],
                ],
                'type' => Type::listOf($userType),
                'resolve' => function ($user, $args) use ($userLoader, $dbh) {
                    $sth = $dbh->prepare('SELECT toID FROM friends WHERE fromID=:userID LIMIT :first');
                    $sth->bindParam(':userID', $user['id'], PDO::PARAM_INT);
                    $sth->bindParam(':first', $args['first'], PDO::PARAM_INT);
                    $friendIDs = $sth->execute();

                    return $userLoader->loadMany($friendIDs);
                }
            ]
        ];
    }
]);
sh
composer