Am scris o clasa simpla ce reprezinta un container de dependente( dependency injection container ), as vrea sa stiu daca sunt pe calea cea buna, incerc sa aplic SOLID in tot ceea ce fac, insa nu am asa de multa experienta.
<?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('Container: 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 . ' was not found in the container');
}
}
}