开发者

CodeIgniter: Lifecycle of the Controllers

The text is quite long, the question is actually simple and written in bold. The other text is only for trying to explain the problem.

I have recently started to use CodeIgniter for developing my website. Currently, I'm writing a side menu where you can filter the items showed in the view (basic e-commerce functionality).

The idea I had was to have an array in my Shop-controller where I开发者_JAVA技巧 store my filtering values which are passed to and from my filterview, so the filter menu kan handle several types of filters.

The problem is that it seems like the constructor of the controller is run each time the controller is called. I thought that the controller was constructed only once when the user enters the website. I'm pretty new at website devlopment and am mainly a C++-guy, so this seems a bit strange for me.

My question is pretty simple actually: Is it true that the controller instance is created at each call to a controller function? Otherwise, what am I doing wrong to cause the controller instance to be reinstantiated at each controller call...

I hope that my question is not too fuzzy. It is important for me to understand the lifecycle behaviour of CodeIgniter to be able to find a simple solution for this. I would like to avoid using $_SESSION, because I would like to use a OOP like solution.


Is it true that the controller instance is created at each call to a controller function? Otherwise, what am I doing wrong to cause the controller instance to be reinstantiated at each controller call..

Yes, the controller instance is re-instantiated every time you make a call to that controller. In CodeIgniter, there is no such thing as a persistent instance of your controller for each user interacting with your application (unlike single-user apps built in C++). What you do have is session management, where you use Session variables to store data persistent to that particular session between the user's browser and your web server (more). Another way to do this is by using cookies. I personally prefer session over cookies.

There is no harm in using $_SESSION for the purpose of your filter, and it is not against OOP principles. What matters is how you use the data stored in your Session variable once your controller instance has loaded ( that's where the OOP concepts come into play).


Shivaas, the same answer can by safely used with models? What about autoloading models? I mean, autoloading it's just a way to avoid typing $this->load->model('the_model') when needed? There's no way to use singleton pattern without recurring to use session/database?

private $instance;

function init_model() {
    if ($this->instance === NULL) {
        $this->instance = array();
    }
    return $this->instance;
}

Once init_model exits, the class instance is destroyed so $instance will be always initialized to a new array()?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜