I have a class that act as a service container for managing providers to have a way of dependency injection.
class Container {
private $providers = array(); // providers array
public function __construct() {
}
/**
* Sets the provider
* @param string $name - provider's name
* @param string|object|array|resource|closure - provider
* @param boolean $singleton
*/
public function set($name, $provider, $singleton = false) {
if ($singleton === false || ($singleton === true && !isset($this->providers[$name]))) {
$this->providers[$name] = $provider;
}
}
/**
* Gets the provider
* @param string $name
* @param array $params
* @return string|object|array|resource
*/
public function get($name, $params = array()) {
if (isset($this->providers[$name])) {
if (is_scalar($this->providers[$name]) || (is_object($this->providers[$name]) && !$this->providers[$name] instanceof Closure) || is_resource($this->providers[$name]) || is_array($this->providers[$name]))
return $this->providers[$name];
elseif ($this->providers[$name] instanceof Closure)
// call a callback with an array of parameters
return call_user_func_array($this->providers[$name], $params);
else
return "Provider type isn't correct.";
}
return "Provider " .$name. " doesn't exist.";
} }
Now, I need to implement singleton access if the third parameter in set method is true. Therefore, the set method should always to return the same instance for result if singleton == true. If the provider is not closure, it is treated as a constant.
For example:
$container = new Container();
$dsn = "mysql:host=localhost;dbname=some_name"; // Host and db name
$user = "root"; // MySQL user name
$pass = "root"; // MySQL password
$container->set("db", function($dsn, $user, $pass) {
return new \PDO($dsn, $user, $pass);
}, true);
$db_data = array($dsn, $user, $pass);
$db = $container->get("db", $db_data);
$db2 = $container->get("db", $db_data);
$db === $db2; // This should to return TRUE <--- This is the goal
How can this be resolved? I don't use any of the frameworks, and it should be a simple universal solution, because this is just an example, but otherwise it does not have to be an instance of the PDO class. Provider can be scalar, object, array, resource or closure.