Problem with application wide component

Hi all,

Based on the wiki (this article)) I wrote a simple application wide component:




<?php


class XChangeSingleton extends CApplicationComponent {


    private $_case_id = null;


    public function setCaseID($case_id) {

        $this->_case_id = $case_id;

    }


    public function getCaseID() {

        if (!$this->_case_id) {

            $this->_case_id = 0;

        }

        return $this->_case_id;

    }


}


?>



In main.php I put this code to create an object of that class:




	'components'=>array(

                'xchange'=>array('class'=>'XChangeSingleton'),

                ....



Then I use the following statements to access the component:




Yii::app()->xchange->setCaseId($cur_case_id);

...

 $model->case_id = Yii::app()->xchange->CaseId; 



But the call xchange->CaseId in all cases returns 0. If I follow the flow with the debugger it seems that Yii does not recognize that the xchange component exists and thus creates a new one. Your thoughts on this are highly appreciated. Is it a horrible typo or am I missing something? I am using yii-1.1.11.58da45.

DigiFox

I checked your code in my localhost.No problem for me.

Thanks for the quick response, pity it worked for you :) !

Update: when I set a value for CaseID and retrieve it in the next statement it seems to work. But when I set a value in one action of a controller (Index) and retrieve it in another (Create) it does not work. In that last case a new xchange-object is created.

DigiFox

That’s the way PHP works. The lifespan of a PHP object is (at most) one HTTP request. Store your data in the session if you want it to survive the request.

Ah, that was stupid. Completely forgot about this, no state. Thanks for taking the time to clear this up, phtamas!