mirror of
https://github.com/danog/amp.git
synced 2025-01-22 13:21:16 +01:00
Merge pull request #133 from amphp/env-driver
Allow setting the loop driver via the env
This commit is contained in:
commit
7e500548df
@ -25,6 +25,8 @@ Amp offers different event loop implementations based on various backends. All i
|
||||
|
||||
It's not important to choose one implementation for your application. Amp will automatically select the best available driver. It's perfectly fine to have one of the extensions in production while relying on the `NativeDriver` locally for development.
|
||||
|
||||
If you want to quickly switch implementations during development, e.g. for comparison or testing, you can set the `AMP_LOOP_DRIVER` environment variable to one of the classes. If you use a custom implementation, this only works if the implementation doesn't take any arguments.
|
||||
|
||||
## Event Loop as Task Scheduler
|
||||
|
||||
The first thing we need to understand to program effectively using an event loop is this:
|
||||
|
@ -8,8 +8,14 @@ class DriverFactory {
|
||||
* Creates a new loop instance and chooses the best available driver.
|
||||
*
|
||||
* @return Driver
|
||||
*
|
||||
* @throws \Error If an invalid class has been specified via AMP_LOOP_DRIVER
|
||||
*/
|
||||
public function create(): Driver {
|
||||
if ($driver = $this->createDriverFromEnv()) {
|
||||
return $driver;
|
||||
}
|
||||
|
||||
if (UvDriver::isSupported()) {
|
||||
return new UvDriver;
|
||||
}
|
||||
@ -24,5 +30,30 @@ class DriverFactory {
|
||||
|
||||
return new NativeDriver;
|
||||
}
|
||||
|
||||
private function createDriverFromEnv() {
|
||||
$driver = \getenv("AMP_LOOP_DRIVER");
|
||||
|
||||
if (!$driver) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!\class_exists($driver)) {
|
||||
throw new \Error(\sprintf(
|
||||
"Driver '%s' does not exist.",
|
||||
$driver
|
||||
));
|
||||
}
|
||||
|
||||
if (!\is_subclass_of($driver, Driver::class)) {
|
||||
throw new \Error(\sprintf(
|
||||
"Driver '%s' is not a subclass of '%s'.",
|
||||
$driver,
|
||||
Driver::class
|
||||
));
|
||||
}
|
||||
|
||||
return new $driver;
|
||||
}
|
||||
}
|
||||
// @codeCoverageIgnoreEnd
|
||||
|
Loading…
x
Reference in New Issue
Block a user