1
0
mirror of https://github.com/danog/loop.git synced 2024-12-03 09:47:48 +01:00
loop/examples/2. Advanced/Loop.php

90 lines
1.6 KiB
PHP
Raw Normal View History

2022-12-24 14:36:39 +01:00
<?php declare(strict_types=1);
2020-07-21 22:12:34 +02:00
require 'vendor/autoload.php';
use danog\Loop\Loop;
use function Amp\delay;
class MyLoop extends Loop
{
/**
* Callable.
*
* @var callable
*/
private $callable;
/**
* Loop name.
*
* @var string
*/
private $name;
/**
* Constructor.
*
* @param callable $callable Callable
* @param string $name Loop name
*/
public function __construct(callable $callable, string $name)
{
$this->callable = $callable;
$this->name = $name;
}
/**
* Main loop.
*/
2022-12-24 15:03:00 +01:00
public function loop(): void
2020-07-21 22:12:34 +02:00
{
$callable = $this->callable;
$number = 0;
while (true) {
2022-12-23 20:45:00 +01:00
$number = $callable($number);
2020-07-21 22:12:34 +02:00
echo "$this: $number".PHP_EOL;
}
}
2020-07-22 17:46:05 +02:00
// Optionally, we can also define logging methods
/**
* Started loop.
*
*/
protected function startedLoop(): void
{
parent::startedLoop();
echo "Started loop $this!".PHP_EOL;
}
/**
* Exited loop.
*
*/
protected function exitedLoop(): void
{
parent::exitedLoop();
echo "Exited loop $this!".PHP_EOL;
}
// End of logging methods
2020-07-21 22:12:34 +02:00
/**
* Get loop name.
*
*/
public function __toString(): string
{
return $this->name;
}
}
2022-12-24 14:36:39 +01:00
$function = function (int $number) {
2022-12-24 17:24:51 +01:00
delay(1);
2022-12-24 14:36:39 +01:00
return $number + 1;
};
$loops = [];
for ($x = 0; $x < 10; $x++) {
$loop = new MyLoop($function, "Loop number $x");
$loop->start();
2022-12-24 17:24:51 +01:00
delay(0.1);
2022-12-24 14:36:39 +01:00
$loops []= $loop;
}