<?php namespace Classes;
class Container
{
/**
* An array that contains container's elements
* @var array
*/
private $container = [];
/**
* An array that contains the instances created.
* @var array
*/
private $instances = [];
/**
* Add a new element in the container.
* @param string $name
* @param callable $callable
* @throws \Exception
*/
public function bind($name, callable $callable)
{
if (is_string($name)) {
$this->container[$name] = $callable;
} else {
throw new \Exception('Containe: You have to provide a valid name in the bind method');
}
}
/**
* Resolve an element from container.
* @param string $name
* @return object
*/
public function resolve($name)
{
if (isset($this->container[$name])) {
return call_user_func($this->container[$name]);
} else {
throw new \Exception('Container: The '. $name . ' was not found in the container');
}
}
/**
* Create instances of elements from container.
* @param string $name
*/
public function singleton($name)
{
$this->instances[$name] = $this->resolve($name);
}
/**
* Use the required instance.
* @param string $name
* @return object
* @throws \Exception
*/
public function resolveSingleton($name)
{
if (isset($this->instances[$name])) {
return $this->instances[$name];
} else {
throw new \Exception('Container: The '. $name . ' instance was not found in the container');
}
}
}