2013-08-05 22:05:08 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Alert;
|
|
|
|
|
2014-08-01 21:37:02 +02:00
|
|
|
/**
|
|
|
|
* The event reactor is a truly global thing in single-threaded code. Applications should use
|
|
|
|
* a single reactor per thread. Accidentally using multiple reactors can lead to all manner of
|
|
|
|
* hard-to-debug problems. Should you almost always avoid static and singletons? Yes, and if you
|
|
|
|
* abuse this static factory method it's your fault. However, there is nothing wrong with
|
|
|
|
* asking for a Reactor instance in your code and using lazy injection via this method if it's
|
|
|
|
* not provided.
|
|
|
|
*
|
|
|
|
* DO NOT instantiate multiple event loops in your PHP application!
|
|
|
|
*/
|
2013-08-05 22:05:08 +02:00
|
|
|
class ReactorFactory {
|
2014-08-01 21:37:02 +02:00
|
|
|
private static $reactor;
|
2013-08-05 22:05:08 +02:00
|
|
|
|
2014-08-01 21:37:02 +02:00
|
|
|
/**
|
|
|
|
* Select a global event reactor based on the current environment
|
|
|
|
*
|
|
|
|
* @param callable $factory An optional factory callable to generate the shared reactor yourself
|
2014-08-02 07:09:07 +02:00
|
|
|
* @return \Alert\Reactor
|
2014-08-01 21:37:02 +02:00
|
|
|
*/
|
|
|
|
public static function select(callable $factory = null) {
|
|
|
|
if (self::$reactor) {
|
|
|
|
return self::$reactor;
|
|
|
|
} elseif ($factory) {
|
2014-08-02 07:09:07 +02:00
|
|
|
return self::$reactor = $factory();
|
2014-08-01 21:37:02 +02:00
|
|
|
} elseif (extension_loaded('uv')) {
|
2014-08-02 07:09:07 +02:00
|
|
|
return self::$reactor = new UvReactor;
|
2014-06-11 18:21:46 +02:00
|
|
|
} elseif (extension_loaded('libevent')) {
|
2014-08-02 07:09:07 +02:00
|
|
|
return self::$reactor = new LibeventReactor;
|
2013-08-05 22:05:08 +02:00
|
|
|
} else {
|
2014-08-02 07:09:07 +02:00
|
|
|
return self::$reactor = new NativeReactor;
|
2013-08-05 22:05:08 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|