source: tags/2.1.5/lib/Cart.inc.php

Last change on this file was 377, checked in by quinn, 14 years ago

Releasing trunk as stable version 2.1.5

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