2013-07-10 34 views
0

我已經創建了一個定製的會話模型(我認爲)能夠工作,並且在我的動作控制器中有兩個測試動作。Magento會話getSingleton失敗

的第一個動作是:

public function testAction() { 
    $session = Mage::getSingleton('mymodule/session'); 
    $session->func1('x'); 
    $var1 = Mage::getSingleton('mymodule/session'); 
    //Tracing through this function reveals that everything behaves as expected, 
    //$session is created, modified and then when $var1 is created, the same 
    //reference is returned and the two references refer to the same object 
    //($session === $var1) = true 
} 

第二個動作是:

public function testresultAction() { 
    $session = Mage::getSingleton('mymodule/session'); 
    var_dump($session); 
    //this method does not appear to work, and upon tracing through the 
    //getSingleton it is in fact creating a new session object, NOT returning 
    //the one that already existed. 
} 

我的會話類看起來是這樣的:

class Mystuff_Mymodule_Model_Session extends Mage_Core_Model_Session_Abstract { 
public function __construct() { 
    $namespace = 'Mystuff_Mymodule'; 

    $this->init ($namespace); 
    Mage::dispatchEvent ('mymodule_session_init', array (
      'mymodule_session' => $this 
    )); 

    $this->setData('history', []); 
    $this->setIndex (- 1); 
} 
    public function func1($historyElement){ 
     $history = $this->getData('history'); 
     array_unshift ($history, $historyElement); 
     while (count ($history) > 10) { 
      array_pop ($history); 
     } 
     $this->setData ('history', $history); 
     $this->setIndex(-1); 
    } 
} 

我還修改了testresultAction其他指向只是var_dump($_SESSION),似乎有它的數據,當我做

SO,爲什麼當我打電話給我的testAction(),它創建一個單例並編輯數據時,併發調用testresultAction()是否沒有修改的數據存在,爲什麼它沒有得到先前實例化的單例?

+2

向我們展示您的會話類 –

+0

@碧西爲什麼要重要?那裏被調用的唯一方法已經顯示出來了? – Nanos

+0

你的會話類正在擴展'Mage_Core_Model_Session_Abstract'類我希望,同意Bixi,我們需要更多的代碼來真正瞭解發生了什麼。 – input

回答

1

存在一個執行範圍的單例(如你所想的那樣)。然而,會話模型實例可以存儲從會話存儲中檢索數據,這意味着雖然您無權訪問相同的模型實例,但您確實擁有實例屬性的持久存儲。

因此,在一個執行範圍,你可以:

$session = Mage::getSingleton('core/session'); 
$session->setFoo(array('bar')); 
//$session->_data['foo'] = array(0=>'bar') 
//aka $_SESSION['core'][0]['bar'] 

然後在接下來的執行範圍:

$session = Mage::getSingleton('core/session'); 
var_dump($session->getFoo()); //array (size=1){ 0 => string 'bar' (length=3) } 

我想你是不是看到$history因爲每次初始化會話模型您將覆蓋它

$this->setData('history', []); 
0

對於那些誰最終不得不以單身問題後

Magento的單身堅持只在頁面

它們取決於註冊表的形式,其堅持通過幾個生活頁面。

至於爲什麼我的數據丟失了,那將是因爲,因爲它是創建一個新的單(因爲它是一個不同的動作,因此,不同的頁面),它被重新初始化數組清空

我無法找到任何文件來驗證單身人士/註冊表的生命週期,所以如果任何人發現請在此處評論/編輯它,完整性

1

你說得對。由於PHP是無狀態的,因此數據沒有放到會話中,只存在於請求 - 響應生命週期中。有了getSingleton,你只需獲取一個實例化對象,如果它已經產生了。