Skip to content

Commit 0c84e81

Browse files
authored
Merge pull request #4 from mcg-web/removed-all-event-references
Removed all eventLoop references
2 parents ba33d6f + c4dd048 commit 0c84e81

File tree

8 files changed

+184
-232
lines changed

8 files changed

+184
-232
lines changed

.travis.yml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,5 +29,4 @@ install: composer update --prefer-dist --no-interaction
2929
script: if [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then phpunit -d xdebug.max_nesting_level=1000 --debug --coverage-clover build/logs/clover.xml; else phpunit --debug; fi
3030

3131
after_success:
32-
- composer require "satooshi/php-coveralls:^1.0"
33-
- travis_retry php vendor/bin/coveralls -v
32+
- if [ "$TRAVIS_PHP_VERSION" == "5.6" ]; then composer require "satooshi/php-coveralls:^1.0" && travis_retry php vendor/bin/coveralls -v; fi

README.md

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ data sources such as databases or web services via batching and caching.
1111

1212
## Requirements
1313

14-
* This library require [React/Promise](https://github.com/reactphp/promise) and PHP >= 5.5 to works.
15-
* The [React/EventLoop](https://github.com/reactphp/event-loop) component are **totally optional** (see `await` method for more details).
14+
This library require [React/Promise](https://github.com/reactphp/promise) and PHP >= 5.5 to works.
1615

1716
## Getting Started
1817

@@ -33,15 +32,15 @@ use Overblog\DataLoader\DataLoader;
3332

3433
$myBatchGetUsers = function ($keys) { /* ... */ };
3534

36-
$userLoader = new DataLoader(new BatchLoadFn($myBatchGetUsers));
35+
$userLoader = new DataLoader($myBatchGetUsers);
3736
```
3837

39-
A batch loading instance accepts a callable callback that accepts an Array of keys, and returns a Promise which
38+
A batch loading callable / callback accepts an Array of keys, and returns a Promise which
4039
resolves to an Array of values.
4140

4241
Then load individual values from the loader. DataLoaderPHP will coalesce all
43-
individual loads which occur within a single frame of execution (a single tick
44-
of the event loop if install or using `await` method) and then call your batch function with all requested keys.
42+
individual loads which occur within a single frame of execution (using `await` method)
43+
and then call your batch function with all requested keys.
4544

4645
```php
4746
$userLoader->load(1)
@@ -80,7 +79,7 @@ your application:
8079

8180
```php
8281
$promise1A = $userLoader->load(1);
83-
$promise1B = userLoader->load(1);
82+
$promise1B = $userLoader->load(1);
8483
var_dump($promise1A === $promise1B); // bool(true)
8584
```
8685

@@ -94,7 +93,7 @@ Here's a simple example using SQL UPDATE to illustrate.
9493
```php
9594
$sql = 'UPDATE users WHERE id=4 SET username="zuck"';
9695
if (true === $conn->query($sql)) {
97-
$userLoader->clear(4);
96+
$userLoader->clear(4);
9897
}
9998
```
10099

@@ -123,12 +122,11 @@ Each `DataLoaderPHP` instance contains a unique memoized cache. Use caution when
123122
used in long-lived applications or those which serve many users with different
124123
access permissions and consider creating a new instance per web request.
125124

126-
##### `new DataLoader(batchLoadFn $batchLoadFn [, Option $options])`
125+
##### `new DataLoader(callable $batchLoadFn [, Option $options])`
127126

128127
Create a new `DataLoaderPHP` given a batch loading instance and options.
129128

130-
- *$batchLoadFn*: A object which accepts a callable callback that accepts an Array of keys,
131-
and returns a Promise which resolves to an Array of values.
129+
- *$batchLoadFn*: A callable / callback which accepts an Array of keys, and returns a Promise which resolves to an Array of values.
132130
- *$options*: An optional object of options:
133131

134132
- *batch*: Default `true`. Set to `false` to disable batching, instead
@@ -164,7 +162,7 @@ list($a, $b) = DataLoader::await($myLoader->loadMany(['a', 'b']);
164162
This is equivalent to the more verbose:
165163

166164
```js
167-
list($a, $b) = await DataLoader::await(\React\Promise\all([
165+
list($a, $b) = DataLoader::await(\React\Promise\all([
168166
$myLoader->load('a'),
169167
$myLoader->load('b')
170168
]);

src/BatchLoadFn.php

Lines changed: 0 additions & 43 deletions
This file was deleted.

src/DataLoader.php

Lines changed: 33 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
class DataLoader
1717
{
1818
/**
19-
* @var BatchLoadFn
19+
* @var callable
2020
*/
2121
private $batchLoadFn;
2222

@@ -35,26 +35,15 @@ class DataLoader
3535
*/
3636
private $queue = [];
3737

38-
/**
39-
* @var null|\React\EventLoop\LoopInterface
40-
*/
41-
private $eventLoop;
42-
43-
/**
44-
* @var Promise
45-
*/
46-
private $resolvedPromise;
47-
4838
/**
4939
* @var self[]
5040
*/
5141
private static $instances = [];
5242

53-
public function __construct(BatchLoadFn $batchLoadFn, Option $options = null)
43+
public function __construct(callable $batchLoadFn, Option $options = null)
5444
{
5545
$this->batchLoadFn = $batchLoadFn;
5646
$this->options = $options ?: new Option();
57-
$this->eventLoop = class_exists('React\\EventLoop\\Factory') ? \React\EventLoop\Factory::create() : null;
5847
$this->promiseCache = $this->options->getCacheMap();
5948
self::$instances[] = $this;
6049
}
@@ -97,12 +86,7 @@ function ($resolve, $reject) use (&$promise, $key, $shouldBatch) {
9786
// A single dispatch should be scheduled per queue at the time when the
9887
// queue changes from "empty" to "full".
9988
if (count($this->queue) === 1) {
100-
if ($shouldBatch) {
101-
// If batching, schedule a task to dispatch the queue.
102-
$this->enqueuePostPromiseJob(function () {
103-
$this->dispatchQueue();
104-
});
105-
} else {
89+
if (!$shouldBatch) {
10690
// Otherwise dispatch the (queue of one) immediately.
10791
$this->dispatchQueue();
10892
}
@@ -124,11 +108,11 @@ function (callable $resolve, callable $reject) {
124108
/**
125109
* Loads multiple keys, promising an array of values:
126110
*
127-
* [$a, $b] = $myLoader->loadMany(['a', 'b']);
111+
* list($a, $b) = $myLoader->loadMany(['a', 'b']);
128112
*
129113
* This is equivalent to the more verbose:
130114
*
131-
* [$a, $b] = \React\Promise\all([
115+
* list($a, $b) = \React\Promise\all([
132116
* $myLoader->load('a'),
133117
* $myLoader->load('b')
134118
* ]);
@@ -139,7 +123,7 @@ function (callable $resolve, callable $reject) {
139123
public function loadMany($keys)
140124
{
141125
if (!is_array($keys) && !$keys instanceof \Traversable) {
142-
throw new \InvalidArgumentException(sprintf('The %s function must be called with Array<key> but got: %s.', __METHOD__, gettype($keys)));
126+
throw new \InvalidArgumentException(sprintf('The "%s" method must be called with Array<key> but got: %s.', __METHOD__, gettype($keys)));
143127
}
144128
return \React\Promise\all(array_map(
145129
function ($key) {
@@ -207,7 +191,9 @@ public function __destruct()
207191
if ($this->needProcess()) {
208192
foreach ($this->queue as $data) {
209193
try {
210-
$data['promise']->cancel();
194+
/** @var Promise $promise */
195+
$promise = $data['promise'];
196+
$promise->cancel();
211197
} catch (\Exception $e) {
212198
// no need to do nothing if cancel failed
213199
}
@@ -243,51 +229,45 @@ public static function await($promise = null, $unwrap = true)
243229
{
244230
self::awaitInstances();
245231

246-
if (null !== $promise) {
247-
$resolvedValue = null;
248-
$exception = null;
232+
if (null === $promise) {
233+
return null;
234+
}
235+
$resolvedValue = null;
236+
$exception = null;
249237

250-
if (!is_callable([$promise, 'then'])) {
251-
throw new \InvalidArgumentException('Promise must have a "then" method.');
252-
}
238+
if (!is_callable([$promise, 'then'])) {
239+
throw new \InvalidArgumentException(sprintf('The "%s" method must be called with a Promise ("then" method).', __METHOD__));
240+
}
253241

254-
$promise->then(function ($values) use (&$resolvedValue) {
255-
$resolvedValue = $values;
256-
}, function ($reason) use (&$exception) {
257-
$exception = $reason;
258-
});
259-
if ($exception instanceof \Exception) {
260-
if (!$unwrap) {
261-
return $exception;
262-
}
263-
throw $exception;
242+
$promise->then(function ($values) use (&$resolvedValue) {
243+
$resolvedValue = $values;
244+
}, function ($reason) use (&$exception) {
245+
$exception = $reason;
246+
});
247+
if ($exception instanceof \Exception) {
248+
if (!$unwrap) {
249+
return $exception;
264250
}
265-
266-
return $resolvedValue;
251+
throw $exception;
267252
}
253+
254+
return $resolvedValue;
268255
}
269256

270257
private static function awaitInstances()
271258
{
272259
$dataLoaders = self::$instances;
273-
if (empty($dataLoaders)) {
274-
return;
275-
}
260+
if (!empty($dataLoaders)) {
261+
$wait = true;
276262

277-
$wait = true;
278-
279-
while ($wait) {
280-
foreach ($dataLoaders as $dataLoader) {
281-
try {
263+
while ($wait) {
264+
foreach ($dataLoaders as $dataLoader) {
282265
if (!$dataLoader || !$dataLoader->needProcess()) {
283266
$wait = false;
284267
continue;
285268
}
286269
$wait = true;
287270
$dataLoader->process();
288-
} catch (\Exception $e) {
289-
$wait = false;
290-
continue;
291271
}
292272
}
293273
}
@@ -305,27 +285,11 @@ private function checkKey($key, $method)
305285
{
306286
if (null === $key) {
307287
throw new \InvalidArgumentException(
308-
sprintf('The %s function must be called with a value, but got: %s.', $method, gettype($key))
288+
sprintf('The "%s" method must be called with a value, but got: %s.', $method, gettype($key))
309289
);
310290
}
311291
}
312292

313-
/**
314-
* @param $fn
315-
*/
316-
private function enqueuePostPromiseJob($fn)
317-
{
318-
if (!$this->resolvedPromise) {
319-
$this->resolvedPromise = \React\Promise\resolve();
320-
}
321-
322-
if ($this->eventLoop) {
323-
$this->resolvedPromise->then(function () use ($fn) {
324-
$this->eventLoop->nextTick($fn);
325-
});
326-
}
327-
}
328-
329293
/**
330294
* Given the current state of a Loader instance, perform a batch load
331295
* from its current queue.

0 commit comments

Comments
 (0)