Professional CodeIgniter

(singke) #1

Adding Products to a Shopping Cart


110


Shopping Cart, but displaying all products in the cart as well. All you have to do is check for the
presence of a product ID in the URI segment.

Once you have that information, you can extract the product from the database into an array, and if that
array has values in it, extract what you need and drop the data from the array into a custom session
variable called cart. Of course, the session variable itself has to be checked to make sure you ’ re not
overwriting data, and that requires some looping and decision trees.

It would be very easy to put all of this data wrangling directly in the controller, but since it ’ s likely that
you ’ ll need this kind of data handling in other parts of your application, it ’ s best to create a new model
(call it MOrders because it is the Model for Orders — it ’ s the naming convention adopted in Chapter 3 ).
Although no database table exists at the moment for this information (it ’ s all handled with PHP sessions),
you might expand the Shopping Cart to include cookies, database tables, or even flat files at a later date.
It doesn ’ t matter. In an MVC context, if you ’ re processing data, do as much as you can in the model.

First, create a new model called MOrders (save it as /system/application/models/morders.php). Then
create an updateCart() function. The updateCart() function takes two arguments: the product ’ s ID
and the full database record for a product. You ’ re going to use $productid as the name of the first
argument (because you ’ re passing in a product ID) and $fullproduct for the second argument (again,
because you ’ re passing in the full product information). The function ’ s first task is to make a copy of the
PHP session array named cart. Then it loops through this copy of the data, looking to see if this
particular product already exists.

If the product doesn ’ t already exist, then add it to the array. If it does exist, increment the product ’ s count
by one. Finally, the entire thing (along with a running total count) is updated in the PHP session, and a
confirmation message is created using CodeIgniter ’ s set_flashdata(). The set_flashdata()
method is new to CodeIgniter 1.6, and it allows you to create a temporary variable that is used
immediately and then discarded. You ’ re going to use it to store a confirmation message and then show it
on the very next page.

< ?php

class MOrders extends Model{
function MOrders(){
parent::Model();
}

function updateCart($productid,$fullproduct){
//pull in existing cart first!
$cart = $_SESSION[‘cart’];
$totalprice = 0;
if (count($fullproduct)){
if (isset($cart[$productid])){
$prevct = $cart[$productid][‘count’];
$prevname = $cart[$productid][‘name’];
$prevname = $cart[$productid][‘price’];

$cart[$productid] = array(
‘name’ = > $prevname,
‘price’ = > $prevprice,
‘count’ = > $prevct + 1
);
Free download pdf