Professional CodeIgniter

(singke) #1

Chapter 5: Building a Shopping Cart xi


109


There ’ s a lot of functionality to build, but the job can be broken down into major tasks. First things first:
Allow users to add products to their Shopping Carts.

First Things First


Before doing anything else, open your Welcome controller and add the following line to the constructor:

function Welcome(){
parent::Controller();
session_start();
}

The session_start() line initializes the PHP sessions that you will need to make the Shopping Cart
work. Without this command, you will just get error messages whenever you try to write to or read from
a PHP session.

Adding Products to a Shopping Cart


Adding products to a user ’ s Shopping Cart is fairly easy. What you need to store is the ID, price, and
number of each product. Why store the price? Because you don ’ t want any back - end product updates
(like price increases) to change the price of products in active Shopping Carts.

The first bit of information, the product ID, is very easy to determine, as in all views you pass in the
product ID to the cart() controller function:

echo anchor(‘welcome/cart/’.$product[‘id’],’add to cart’);

Once again, to build the controller function, you ’ re going to take advantage of smart coding to minimize
your work. The cart() controller function should be able to handle not only adding products to the

Figure 5 - 2
Free download pdf