2015-03-13 54 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