PHP code example of leinonen / php-dataloader

1. Go to this page and download the library: Download leinonen/php-dataloader 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/ */

    

leinonen / php-dataloader example snippets


use leinonen\DataLoader\Dataloader;
use React\EventLoop\Factory;

$eventLoop = Factory::create();

$bandLoader = new DataLoader(
    function ($keys) {
        // Batch load bands with given keys.
    },
    $eventLoop,
    new CacheMap()
);

$bandLoader->load(1)->then(function ($band) {
    echo "Band #${$band->getId()} loaded";
});

$bandLoader->load(2)->then(function ($band) {
    echo "Band #${$band->getId()} loaded";
});

$eventLoop->run(); // The batch function will be called with keys [1, 2] at this point

[
    ['id' => 1, 'name' => 'Mojo Waves'],
    ['id' => 2, 'name' => 'Pleasure Hazard'],
    ['id' => 9, 'name' => 'Leka'],
]

[
    ['id' => 2, 'name' => 'Pleasure Hazard'],
    ['id' => 9, 'name' => 'Leka'],
    null,
    ['id' => 1, 'name' => 'Mojo Waves'],
]

$promise1 = $bandLoader->load(1);
$promise2 = $bandLoader->load(2);

($promise1 === $promise2) // true

$userByIdLoader = new DataLoader(function ($ids) {
  $users = User::findMany($ids);

  // Make sure that the users are on the same order as the given ids for the loader
  $orderedUsers = collect($ids)->map(function ($id) use ($users) {
    return $users->first(function ($user) use ($id) {
      return $user->id === $id;
    });
  });

   return \React\Promise\resolve($orderedUsers);
}, $eventLoopFromIoCContainer, $cacheMapFromIoCContainer);

$usersByIdLoader = new DataLoader(function ($ids) {
    $users = User::find()->where(['id' => $ids])->all();

    $orderedUsers = \array_map(function ($id) use ($users) {
        foreach ($users as $user) {
            if ($user->id === $id) {
                return $user;
            }
        }

        return null;
    }, $ids);

    return \React\Promise\resolve($orderedUsers);
}, $eventLoopFromDiContainer, $cacheMapImplementationFromDiContainer);

$promises = \React\Promise\all([
  $myLoader->load('a'),
  $myLoader->load('b')
]);
bash
composer