簡體   English   中英

Phalcon中的單例組件是真正的單例嗎?

[英]Is a singleton component in phalcon a real singleton?

讓我宣布一個問題:
據我所知,當請求結束時,php將清除它創建的對象和其他數據。

但是正如Phalcon的文件所述:
服務可以注冊為“共享”服務,這意味着它們始終將作為單例。一旦服務被首次解析,每次消費者從容器中檢索到服務時,都將返回相同的實例 ”。

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

我想知道的是:創建共享組件后,在下一個請求時,Phalcon將重用共享組件嗎? 我的意思是phalcon不會創建新的組件實例。

對於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連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM