1 <?php
2
3 namespace DesignPatternsCreationalPool;
4
5 use Countable;
6
7
8 class WorkerPool implements Countable
9 {
10 /**
11 * @var StringReverseWorker[]
12 */
13 private $occupiedWorkers = [];
14
15 /**
16 * @var StringReverseWorker[]
17 */
18 private $freeWorkers = [];
19
20 public function get(): StringReverseWorker
21 {
22 if (count($this->freeWorkers) == 0) {
23 $worker = new StringReverseWorker();
24 } else {
25 $worker = array_pop($this->freeWorkers);
26 }
27
28 $this->occupiedWorkers[spl_object_hash($worker)] = $worker;
29
30 return $worker;
31 }
32
33 public function dispose(StringReverseWorker $worker)
34 {
35 $key = spl_object_hash($worker);
36
37 if (isset($this->occupiedWorkers[$key])) {
38 unset($this->occupiedWorkers[$key]);
39 $this->freeWorkers[$key] = $worker;
40 }
41 }
42
43 public function count(): int
44 {
45 return count($this->occupiedWorkers) + count($this->freeWorkers);
46 }
47 }
48
49 class StringReverseWorker
50 {
51 private $noncestr;
52
53 public function __construct()
54 {
55 $this->noncestr = time().mt_rand(100,999);
56 }
57
58 public function run(string $text)
59 {
60 return strrev($text);
61 }
62 }
63
64 $pool = new WorkerPool();
65 $w1 = $pool->get();
66 $w2 = $pool->get();
67
68 var_dump($w1);
69 echo "<hr/>";
70 var_dump($w2);
71 echo "<hr/>";
72
73 $pool->dispose($w1);
74 $w3 = $pool->get();
75 var_dump($w3);