Question

I'm stuck with the following problem: I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).

class CartItem extends AppModel{

    var $name = "CartItem";

    var $useTable = false;
}

I tried this:

function addToCart(){

    $this->loadModel("Cart");

    $this->layout = false;
    $this->render(false);

    $cart = array();

    $tempcart = unserialize($this->Session->read("cart")); 

    if(isset($tempcart)){
        $cart = $tempcart;
    }

    $productId = $this->request->data("id");

    if(!$this->existsInCart($cart, $productId)){

        $cartItem = new Cart();

        $cartItem->productId = $productId;
        $cartItem->createdAt = date();

        $cart[] = $cartItem;

        $this->Session->write("cart", serialize($cart));

        echo "added";
    }
    else
        echo "duplicate";
}

I think I'm writing these lines wrong:

$tempcart = unserialize($this->Session->read("cart"));

$this->Session->write("cart", serialize($cart));

as I'm not getting data from the session.

Was it helpful?

Solution

You are trying to add the whole Cart object to the session.

You should just add an array, like

$cart[] = array(
    'productId' => $productId,
    'createdAt' => date('Y-m-d H:i:s')
);

If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top