phalcon中的单例成分是真正的单例吗?

时间:2015-03-13 07:46:33

标签: php phalcon

让我宣布一个问题:
据我所知,当请求结束时,php将清除它创建的对象和其他数据。

但正如Phalcon的文件所说: “ Services can be registered as “shared” services this means that they always will act as singletons. Once the service is resolved for the first time the same instance of it is returned every time a consumer retrieve the service from the container ”。

<?php
//Register the session service as "always shared"
$di->set('session', function() {
    //...
}, true);

我想知道的是:创建共享组件后,在下一个请求时,phalcon将重用共享组件?我的意思是phalcon不会创建新的组件实例。

1 个答案:

答案 0 :(得分:1)

对于DI:setShared()和您的示例,,它将符合单身人士的条件。相反,如果你DI::set(..., ..., false)它将使用DI::get(...)创建新实例 - 除非使用DI::getShared()检索它,将根据派生闭包创建新实例并将其保存到{{ 1}}以供将来使用 - 但您总是需要DI,如下所示:

DI::getShared()

和概念证明:

// not shared
$di->set('test', function() {
    $x = new \stdClass();
    $x->test1 = true;

    return $x;
}, false);

// first use creates singletonized instance
$x = $di->getShared('test');
$x->test2 = true; // writing to singleton

// retrieving singletoned instance
var_dump($di->getShared('test'));

// getting fresh instance
var_dump($di->get('test'));

// despite of previous ::get(), still a singleton
var_dump($di->getShared('test'));

为了证明您创建了多少个实例,我建议您在服务中声明析构函数以显示一些输出。无论如何,PHP使用的东西在某些情况下可能会在请求结束后保留​​ - 比如打开的SQL连接。