2015-03-13 56 views
1

让我声明这个问题:
据我所知,当一个请求结束时,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不会创建一个新的组件实例。

+0

每个请求都是一个单独的世界,所有的库都被重新加载并重新创建对象。 – 2015-03-13 07:47:46

+0

所以,你的意思是说,每个请求都需要创建相同的组件,这不是一个真正的单例吗? – 2015-03-13 08:13:21

+0

是的,对于您在http请求中创建的每个对象都是如此,这里没有什么新东西。 “单身人士”总是指在相同请求的背景下。 – 2015-03-13 08:36:53

回答

1

对于DI:setShared()和你的例子,它将满足单身条件。相反,如果你DI::set(..., ..., false)它会创建一个新的实例,每个DI::get(...) - 除非你检索它与DI::getShared(),什么将基于派生闭包创建新实例并将其保存到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')); 

和证明的概念:

object(stdClass)[25] 
    public 'test1' => boolean true 
    public 'test2' => boolean true 

object(stdClass)[26] 
    public 'test1' => boolean true 

object(stdClass)[25] 
    public 'test1' => boolean true 
    public 'test2' => boolean true 

要证明你有多少创建的实例,我在你的服务提出声明析构函数表现出一定的输出。无论如何,有些东西是PHP使用的,在某些情况下可能会在请求结束后保留​​ - 比如打开的SQL连接。

+0

那么,我已经确定它是一个请求中的单身人士。一切都会在不同的请求中创建。 – 2015-03-14 06:10:27

+0

为了从以前的请求恢复组件,你有缓存和会话。 – yergo 2015-03-14 11:56:52