Ronnie Jespersen
Ronnie Jespersen

Reputation: 950

CakePHP save objects state

I'm trying out the cakePHP framework, and I have a question about objects state.

Previously, I have been used to serializing objects and unserializing them upon reload. In that way, objects always keep their state, but I'm not sure if that's the best practice.

What is the best practice to keep track of the products added to the shopping cart and the general state of the model? Do I save the object state somehow in sessions? Or do I keep the data in sessions and rebuild the model when the page is reloaded?

Does cakePHP offer some build-in functionality that I should know about when it comes to objects and states?

Upvotes: 0

Views: 557

Answers (1)

Sam Delaney
Sam Delaney

Reputation: 1305

It seemed fitting to answer your questions in reverse order.

Does cakePHP offer some build-in functionality I should know about when it comes to objects and states?

Yes!, CakePHP has a built in wrapper for the PHP $_SESSION object so you can quickly add and remove objects to and from it with the supplied convenience methods.

What is the best practice to keep track of the products added to the shoopingcart and the general state of the model? Do I save the object state somehow in session? Or do I keep the data in session and rebuild the model if the page is reloaded?

I personally never found the need to persist instances of PHP classes in my applications because all framework objects (e.g. Controllers, Models, etc.) are generally stateless. Since records from the database I stored in associative arrays, there are no problems with serializing them.

The best way to think about the framework is the only thing to have state across page reloads is your database... and Session if you choose to use it.

In your case I would probably do the following (in your Controller):

public function addProductToCart($productId){
    // find the product in the database (model)
    $product => $this->Product->findById($productId);
    // get the existing state of the basket
    $basket = $this->Session->read('basket');
    // just in case the basket hasn't been initialised
    if($basket == null){
        $basket = array();
    }
    // append the basket to the database
    $basket[] = $product;
    // write the basket to the session
    $this->Session->write('basket', $basket);
}

Please do read the documentation as it will show you how to use the Session object in your view as well.

Upvotes: 1

Related Questions