ServiceLocator.php 1003 B
Newer Older
<?php

namespace Hp\Patterns\ServiceLocator;

use InvalidArgumentException;

class ServiceLocator
{
    private array $services = [];

    private array $instantiated = [];

    public function addInstance(string $class, ServiceInterface $service): void
    {
        $this->instantiated[$class] = $service;
    }

    public function addClass(string $class, array $params): void
    {
        $this->services[$class] = $params;
    }

    public function has(string $class): bool
    {
        return isset($this->instantiated[$class]) || isset($this->services[$class]);
    }

    public function get(string $class): ServiceInterface
    {
        if (isset($this->instantiated[$class])) {
            return $this->instantiated[$class];
        }

        $object = new $class(...$this->services[$class]);

        if (!$object instanceof ServiceInterface) {
            throw new InvalidArgumentException();
        }

        $this->instantiated[$class] = $object;

        return $object;
    }
}