Здравствуйте, изучаю паттерны проектирования. В данном случае Dependency Injection Container. Нужен совет от опытных коллег.
Есть базовая модель
abstract class Model
{
protected $connection;
public function __construct()
{
$this->connection = (new PDOMysqlConnection)->getConnection();
}
}
Модель
namespace models;
class User extends Model
{
public function getAll(): array
{
return $this->connection->executeQuery('SELECT * FROM users')->fetchAllAssociative();
}
}
Контроллер
namespace controllers;
use models\User as UserModel;
class User extends Controller
{
private $model;
public function index()
{
$this->model = new UserModel;
}
}
При каждом создании нового объекта модели, будет создаваться новое соединение с базой данных. Обычно соединение делал с помощью Singleton. Подскажите пожалуйста, есть ли возможность решить это с помощью DIC?
Хранить зависимости в статическом свойстве-массиве?
Код контейнера
class Container implements ContainerInterface
{
private array $instances = [];
public function set(string $id, callable $resolver): void
{
$this->instances[$id] = $resolver;
}
public function has(string $id): bool
{
return isset($this->instances[$id]);
}
public function get(string $id)
{
if (!$this->has($id)) {
throw new NotFoundException("Dependency '$id' not found in the container.");
}
return $this->instances[$id]($this);
}
public function bind(string $id)
{
return $this->buildDependencies($id);
}
private function buildDependencies(string $className)
{
$reflector = new \ReflectionClass($className);
if (empty($constructor = $reflector->getConstructor())
|| empty($parameters = $constructor->getParameters())) {
return new $className;
}
$dependencies = [];
foreach ($parameters as $parameter) {
$dependency = $parameter->getType()?->getName();
$dependencies[] = $this->get($dependency);
}
return $reflector->newInstanceArgs($dependencies);
}
}