2

I'm using Zend Framework with Propel. It's easy enough to use Propel objects as my models for things that are stored in the database, but how do I go about creating a custom model such as a shopping cart that uses propel objects?

I'm thinking of creating a class called CartItem and Cart. If CartItem contains a propel Product class, and Cart contains an array of CartItems, this seems very expensive to store in a session. Normally I'd just use an array, but I'm trying to get better with OOP

1

1 Answer 1

1

You could use PHP's Interface Serializable: http://php.net/manual/de/class.serializable.php

You can use it to convert an instance of your cart into a more efficient value (you define, what exactly is stored), which is in your case a two-dimensional array.

Try something like this:

<?php

class Cart implements Serializable {

    // your normal code for the Cart class

    public function serialize() {
        $cartData = array();
        foreach($this->cartItems as $item) {
            $cartData[] = array(
                'count' => $item->getCount(),
                'productId' => $item->getId()
            );
        }
        return serialize($cartData);
    }

    public function unserialize($cartData) {
        $this->cartItem = array();
        foreach($cartData as $item) {
            // replace this with the appropriate propel code
            $product = loadProductWithPropelById($item['id']);
            $this->cartItems[] = new CartItem($item['count'], $product);
        }
    }

}

?>

Then use serialize to store the cart in the session and retrieve it:

<?php

// Store cart to session
$_SESSION['cart'] = serialize($cart);

// get cart from session
$cart = unserialize($_SESSION['cart']);

?>

Good Luck with your Project!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.