source: trunk/lib/Cart.inc.php @ 356

Last change on this file since 356 was 356, checked in by quinn, 15 years ago

Missing break statements to Cart::sum().

File size: 9.1 KB
Line 
1<?php
2/**
3 * Cart.inc.php
4 * code by strangecode :: www.strangecode.com :: this document contains copyrighted information
5 *
6 * Class description goes here...
7 *
8 * @author  Quinn Comendant <quinn@strangecode.com>
9 * @version 1.0
10 *
11 * Example of use:
12---------------------------------------------------------------------
13$cart = new Cart();
14
15switch (getFormData('op')) {
16case 'add' :
17    // User clicks an "Add to cart" button.
18    if ($product_id = getFormData('product_id')) {
19        $qid = $db->query("SELECT * FROM product_tbl WHERE product_id = '" . $db->escapeString($product_id) . "'");
20        if ($p = mysql_fetch_assoc($qid)) {
21            $cart->add($product_id, $p['price'], 1, array(
22                'title' => $p['title'],
23                'shipping' => $p['shipping'],
24                'weight' => $p['weight'],
25            ));
26        }
27    }
28    break;
29
30case 'remove' :
31    // User clicks a "Remove item" button.
32    $cart->remove(getFormData('product_id'));
33    break;
34
35case 'qty' :
36    // User changes the quantity of an item.
37    $cart->setQty(getFormData('product_id'), getFormData('qty'));
38    break;
39
40case 'view' :
41default :
42    // User views cart.
43    foreach ($cart->getList() as $item) {
44        printf("Item: %s\nQty: %s\nPrice: %s\n\n", $item['title'], $item['quantity'], $item['price']);
45    }
46    break;
47}
48---------------------------------------------------------------------
49 */
50class Cart {
51
52    // Namespace of this instance.
53    var $_ns;
54
55    // Configuration parameters for this object.
56    var $_params = array(
57    );
58
59    /**
60     * Cart constructor.
61     */
62    function Cart($namespace='')
63    {
64        $app =& App::getInstance();
65
66        $this->_ns = $namespace;
67       
68        // Initialize.
69        if (!isset($_SESSION['_cart'][$this->_ns])) {
70            $this->clear();
71        }
72    }
73
74    /**
75     * Set the params of this object.
76     *
77     * @param  array $params   Array of param keys and values to set.
78     */
79    function setParam($params=null)
80    {
81        if (isset($params) && is_array($params)) {
82            // Merge new parameters with old overriding only those passed.
83            $this->_params = array_merge($this->_params, $params);
84        }
85    }
86
87    /**
88     * Return the value of a parameter, if it exists.
89     *
90     * @access public
91     * @param string $param        Which parameter to return.
92     * @return mixed               Configured parameter value.
93     */
94    function getParam($param)
95    {
96        $app =& App::getInstance();
97   
98        if (isset($this->_params[$param])) {
99            return $this->_params[$param];
100        } else {
101            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
102            return null;
103        }
104    }
105
106    /*
107    * Add an item to the cart. If called twice for one item it will add the quantities together.
108    *
109    * @access   public
110    * @param    string  $item_id    A unique ID for the item
111    * @param    float   $price      Price-per-quantity-unit for the item
112    * @param    float   $quantity   Quantity of items (can be fractional unites?)
113    * @param    array   $specs      An array of additional specifications (title, weight, etc)
114    * @return   float               The new adjusted quantity of this item.
115    * @author   Quinn Comendant <quinn@strangecode.com>
116    * @version  1.0
117    * @since    11 Mar 2008 18:59:37
118    */
119    function add($item_id, $price, $quantity=1, $specs=array())
120    {
121        $app =& App::getInstance();
122       
123        // Include any previously added items in the total quantity.
124        $quantity += isset($_SESSION['_cart'][$this->_ns]['items'][$item_id]) ? $_SESSION['_cart'][$this->_ns]['items'][$item_id]['quantity'] : 0;
125       
126        // Add item with adjusted quantity and merge in additional specs.
127        $_SESSION['_cart'][$this->_ns]['items'][$item_id] = array_merge($specs, array(
128            'quantity' => $quantity,
129            'price' => $price,
130            'extended_price' => $quantity * $price,
131        ));
132       
133        $app->logMsg(sprintf('Added %s %s to cart (%s)', $quantity, $item_id, truncate(getDump($specs, true), 128, 'end')), LOG_DEBUG, __FILE__, __LINE__);
134       
135        return $quantity;
136    }
137   
138    /*
139    * Set the absolute quantity value of a specified item in a cart.
140    *
141    * @access   public
142    * @param   
143    * @return   
144    * @author   Quinn Comendant <quinn@strangecode.com>
145    * @version  1.0
146    * @since    10 May 2008 16:42:25
147    */
148    function setQty($item_id, $quantity)
149    {
150        if ($quantity <= 0) {
151            $this->remove($item_id);
152        } else {
153            if (isset($_SESSION['_cart'][$this->_ns]['items'][$item_id])) {
154                $item = $_SESSION['_cart'][$this->_ns]['items'][$item_id];
155                $_SESSION['_cart'][$this->_ns]['items'][$item_id] = array_merge($item, array(
156                    'quantity' => $quantity,
157                    'extended_price' => $quantity * $item['price'],
158                ));
159                return true;
160            } else {
161                return false;
162            }
163            return true;
164        }
165    }
166   
167    /*
168    * Set the absolute price value of a specified item in a cart.
169    *
170    * @access   public
171    * @param   
172    * @return   
173    * @author   Quinn Comendant <quinn@strangecode.com>
174    * @version  1.0
175    * @since    10 May 2008 16:42:25
176    */
177    function setPrice($item_id, $price)
178    {
179        if (isset($_SESSION['_cart'][$this->_ns]['items'][$item_id])) {
180            $item = $_SESSION['_cart'][$this->_ns]['items'][$item_id];
181            $_SESSION['_cart'][$this->_ns]['items'][$item_id] = array_merge($item, array(
182                'price' => $price,
183                'extended_price' => $price * $item['quantity'],
184            ));
185            return true;
186        } else {
187            return false;
188        }
189    }
190   
191    /*
192    * Remove an item from the cart.
193    *
194    * @access   public
195    * @param    string  $item_id    Item to remove from cart.
196    * @author   Quinn Comendant <quinn@strangecode.com>
197    * @version  1.0
198    * @since    11 Mar 2008 18:59:48
199    */
200    function remove($item_id)
201    {
202        $app =& App::getInstance();
203       
204        if (isset($_SESSION['_cart'][$this->_ns]['items'][$item_id])) {
205            unset($_SESSION['_cart'][$this->_ns]['items'][$item_id]);
206            $app->logMsg(sprintf('Removed %s from cart', $item_id), LOG_DEBUG, __FILE__, __LINE__);
207            return true;
208        } else {
209            return false;
210        }
211    }
212   
213    /*
214    * Return the value matching key for a specified item.
215    *
216    * @access   public
217    * @param    string  $item_id    The ID of the cart item to retrieve.
218    * @param    string  $spec_key   The key of the value to return.
219    * @return   mixed               The value, or false if not found.
220    * @author   Quinn Comendant <quinn@strangecode.com>
221    * @version  1.0
222    * @since    11 Mar 2008 18:59:55
223    */
224    function get($item_id, $spec_key)
225    {
226        if (isset($_SESSION['_cart'][$this->_ns]['items'][$item_id][$spec_key])) {
227            return $_SESSION['_cart'][$this->_ns]['items'][$item_id][$spec_key];
228        }
229        return false;
230    }
231   
232    /*
233    * Return an array of the items in cart.
234    *
235    * @access   public
236    * @return   array   Array of cart items.
237    * @author   Quinn Comendant <quinn@strangecode.com>
238    * @version  1.0
239    * @since    11 Mar 2008 18:59:55
240    */
241    function getList()
242    {
243        return $_SESSION['_cart'][$this->_ns]['items'];
244    }
245   
246    /*
247    * Return the sum of the numeric values stored under the specified key for cart items.
248    * 0 will be returned if key is invalid or not filled with numeric values.
249    * Most commonly, $cart->sum() will be called when checking out to retrieve the total
250    * cost of the items in the cart.
251    *
252    * @access   public
253    * @param    string  $key    The spec key to sum.
254    * @return   float           The total added by all the found values.
255    * @author   Quinn Comendant <quinn@strangecode.com>
256    * @version  1.0
257    * @since    11 Mar 2008 19:00:12
258    */
259    function sum($key='extended_price')
260    {
261        global $app;
262
263        $sum = 0;
264        switch ($key) {
265        case 'items' :
266            $sum = sizeof($_SESSION['_cart'][$this->_ns]['items']);
267            break;
268
269        case 'extended_price' :
270            foreach ($_SESSION['_cart'][$this->_ns]['items'] as $item_id => $specs) {
271                $sum += isset($specs[$key]) && is_numeric($specs[$key]) ? $specs[$key] : 0;
272            }
273            break;
274
275        default :
276            // Retreive arbitrary values stored in the cart (shipping, air miles, etc).
277            foreach ($_SESSION['_cart'][$this->_ns]['items'] as $item_id => $specs) {
278                $sum += isset($specs[$key]) && is_numeric($specs[$key]) ? $specs[$key] * $specs['quantity'] : 0;
279            }
280            break;
281        }
282       
283        return $sum;
284    }
285
286    /**
287     * Resets the $_SESSION cart array. This should be executed with the same consideration
288     * as $auth->clear(), such as when logging out.
289     */
290    function clear()
291    {
292        $_SESSION['_cart'][$this->_ns] = array(
293            'items' => array(),
294        );
295    }
296}
297
298
299?>
Note: See TracBrowser for help on using the repository browser.