Professional CodeIgniter

(singke) #1

Chapter 5: Building a Shopping Cart


111


}else{
$cart[$productid] = array(
‘name’ = > $fullproduct[‘name’],
‘price’ = > $fullproduct[‘price’],
‘count’ = > 1
);
}

foreach ($cart as $id = > $product){
$totalprice += $product[‘price’] * $product[‘count’];
}
$_SESSION[‘totalprice’] = $totalprice;
$_SESSION[‘cart’] = $cart;
$this- > session- > set_flashdata(‘conf_msg’, “We’ve added this product to your
cart.”);
}
}

}//end class
? >

The beauty of this setup lies in the fact that if the product isn ’ t in the user ’ s Shopping Cart, then it is
added along with whatever price is currently available from the database. If the product is already in the
Shopping Cart, then it simply updates the count, but nothing else.

All of this processing may seem like a lot of work, but it will save you lots of processing in the view.

Now for the controller function named cart(). All you have to do to keep things running smoothly is
pass in an argument that corresponds with the product ID. In other controller functions, you ’ ve been
using $id as the name of this argument, but in this case, it makes sense to use $productid.


Please note that this $productid bears absolutely zero resemblance to the $productid used in the
model. All you ’ re trying to do is use nomenclature that is semantically valid. You could have passed in a
variable named $buffyTheVampire or $myproduct or simply $id. In this case, you ’ ve opted for
$productid. In any case, if the product ID passed to the function has an associated value, then run the
updateCart() function in MOrders, and redirect users back to the product page. If the passed in
product ID is less than 0, display everything that ’ s saved in the user ’ s Shopping Cart (this is discussed
later, in the section, “ Displaying the Shopping Cart to the User ” ).


function cart($productid){
if ($productid > 0){

$fullproduct = $this- > MProducts- > getProduct($productid);
$this- > MOrders- > updateCart($productid,$fullproduct);
redirect(‘welcome/product/’.$productid, ‘refresh’);
}else{
$data[‘title’] = “Claudia’s Kids | Shopping Cart”;
if (count($_SESSION[‘cart’]) == true){
$data[‘main’] = ‘’;
$nav[‘navlist’] = $this- > MCats- > getCategoriesNav();
$this- > load- > vars($data);
$this- > load- > view(‘template’);
Free download pdf