Skip to content

Commit 0e4194b

Browse files
committed
Add LoopDriverFactory
The LoopDriverFactory SHOULD be used by driver implementations to set a default event loop driver. This can be achieved by having a Composer autoloader like that: { "autoload": { "files": ["src/bootstrap.php"] } } Where src/bootstrap.php contains the following code: use Interop\Async\EventLoop\LoopDriverFactory; class MyDriverFactory implements LoopDriverFactory { public function create() { return new MyDriver(); } } Loop::setFactory(new MyDriverFactory()); This ensures the user doesn't have to care about setting the actual driver. A user just has to require the specific event loop driver package he / she wants to use.
1 parent 662cfdc commit 0e4194b

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

src/Loop.php

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,24 @@ final class Loop
66
{
77
use Registry;
88

9+
/**
10+
* @var LoopDriverFactory
11+
*/
12+
private static $factory = null;
13+
914
/**
1015
* @var LoopDriver
1116
*/
1217
private static $driver = null;
1318

19+
/**
20+
* Set the factory to be used to create a driver if none is passed to
21+
* self::execute.
22+
*/
23+
public static function setFactory(LoopDriverFactory $factory = null) {
24+
self::$factory = $factory;
25+
}
26+
1427
/**
1528
* Execute a callback within the scope of an event loop driver.
1629
*
@@ -19,11 +32,12 @@ final class Loop
1932
*
2033
* @return void
2134
*/
22-
public static function execute(callable $callback, LoopDriver $driver)
35+
public static function execute(callable $callback, LoopDriver $driver = null)
2336
{
24-
$previousDriver = self::$driver;
37+
$driver = $driver ?: $this->createDriver();
2538
$previousRegistry = self::$registry;
2639

40+
$previousDriver = self::$driver;
2741
self::$driver = $driver;
2842
self::$registry = [];
2943

@@ -37,6 +51,20 @@ public static function execute(callable $callback, LoopDriver $driver)
3751
}
3852
}
3953

54+
/**
55+
* Create a new driver if a factory is present, otherwise throw.
56+
*
57+
* @throws \LogicException if no factory is set
58+
*/
59+
private static function createDriver()
60+
{
61+
if (self::$factory === null) {
62+
throw new \LogicException("Can't create an event loop driver without a factory.");
63+
}
64+
65+
return self::$factory->create();
66+
}
67+
4068
/**
4169
* Retrieve the event loop driver that is in scope.
4270
*

src/LoopDriverFactory.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace Interop\Async\EventLoop;
4+
5+
interface LoopDriverFactory
6+
{
7+
/**
8+
* Create a new event loop driver instance.
9+
*
10+
* @return LoopDriver
11+
*/
12+
public function create();
13+
}

0 commit comments

Comments
 (0)