Add Container class

This class is used as DI Container for easier injecting classes in integration tests.
It can be also reused during a standalone usage.
[MAILPOET-6216]
This commit is contained in:
Jan Lysý
2024-09-18 18:11:22 +02:00
committed by Jan Lysý
parent 1af3c09422
commit 4424a33624
2 changed files with 72 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
<?php declare(strict_types = 1);
namespace MailPoet\EmailEditor;
class Container {
protected array $services = [];
protected array $instances = [];
public function set(string $name, callable $callable): void {
$this->services[$name] = $callable;
}
public function get(string $name) {
// Check if the service is already instantiated
if (isset($this->instances[$name])) {
return $this->instances[$name];
}
// Check if the service is registered
if (!isset($this->services[$name])) {
throw new \Exception("Service not found: $name");
}
$this->instances[$name] = $this->services[$name]($this);
return $this->instances[$name];
}
}