<?php
namespace IntellexApps\PHP\UploadFile\Domain\Service;

class ServiceContainer {
    var $instances = [];

    private function initializeServices()
    {
        $services = $this->getServices();

        foreach($services as $name => $class) {
            $this->instances[$name] = new $class($this);
        }

        foreach($this->instances as $name => $instance) {
            $instance->init();
        }
    }

    /**
     * Get service
     *
     * @param $serviceName
     * @return mixed
     * @throws \Exception
     */
    public function get($serviceName)
    {
        if(!isset($this->instances[$serviceName])) {
            throw new \Exception(__('Service %s not found!', $serviceName));
        }

        return $this->instances[$serviceName];
    }

    /**
     * Get services
     *
     * @return mixed
     */
    private function getServices()
    {
        return require CONFIG_DIR . 'services.php';
    }

    /**
     * Get instance of service container
     *
     * @return bool|static
     */
    public static function instance()
    {
        static $instance = false;
        if( $instance === false )
        {
            $instance = new static();
            $instance->initializeServices();
        }

        return $instance;
    }

    private function __construct() {}

    private function __clone() {}

    private function __sleep() {}

    private function __wakeup() {}

}
