dongxun3777 2015-11-14 01:39
浏览 31

如何在服务容器中实现单例访问?

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.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
    • ¥15 ETLCloud 处理json多层级问题
    • ¥15 matlab中使用gurobi时报错
    • ¥15 这个主板怎么能扩出一两个sata口
    • ¥15 不是,这到底错哪儿了😭
    • ¥15 2020长安杯与连接网探
    • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么