Creating a basic cart

In this section, we will be creating the basic files necessary to run a cart. Later in the chapter, we will be adding greater functionality to it, but first let's prepare. We will be creating the following four files:

  • path/to/codeigniter/application/controllers/shop.php: This controller will handle any customer interaction between the views and the model, such as handling any forms and controlling the customer's journey through the cart.
  • path/to/codeigniter/application/models/shop_model.php: This model will handle any database interaction between the controller and the database. It will contain functions to fetch products and, product categories, and later in the chapter, to save the cart to the database.
  • path/to/codeigniter/application/views/shop/display_cart.php: This view will display a summary of a customer's cart at any one time, and allow that customer to amend the quantities of items in their cart.
  • path/to/codeigniter/application/views/shop/view_products.php: This view will display products from the cart.products table in the database, and provide options to allow the customer to add items to their cart.

How to do it...

We're going to create the following four files:

  • /path/to/codeigniter/application/controllers/shop.php
  • /path/to/codeigniter/application/models/shop_model.php
  • /path/to/codeigniter/application/views/shop/display_cart.php
  • /path/to/codeigniter/application/views/shop/display_products.php
  1. Copy the following code into the, /path/to/codeigniter/application/controllers/shop.php file:
    <?php if (!defined('BASEPATH')) exit('No direct script access allowed'),
    
    class Shop extends CI_Controller {
        function __construct() {
            parent::__construct();
            $this->load->library('cart'),
            $this->load->helper('form'),
            $this->load->helper('url'),
            $this->load->helper('security'),
            $this->load->model('Shop_model'),
        }
    
        public function index() {
            $data['query'] = $this->Shop_model->get_all_products();
            $this->load->view('shop/display_products', $data);
        }
    
        public function add() {
            $product_id = $this->uri->segment(3);
            $query = $this->Shop_model->get_product_details($product_id);
            foreach($query->result() as $row) {
                $data = array(
                    'id'   => $row->product_id,
                    'qty' => 1,
                    'price'  => $row->product_price,
                    'name' => $row->product_name,
                 );
            }
    
            $this->cart->insert($data);
            $this->load->view('shop/display_cart', $data);
        }
    
        public function update_cart() {
            $data = array();
            $i = 0;
    
            foreach($this->input->post() as $item) {
                    $data[$i]['rowid']  = $item['rowid'];
                    $data[$i]['qty']    = $item['qty'];
                    $i++;
            }
    
            $this->cart->update($data);
            redirect('shop/display_cart'),
        }
    
        public function display_cart() {
            $this->load->view('shop/display_cart'),
        }
    
        public function clear_cart() {
            $this->cart->destroy();
            redirect('index'),
        }
    }
  2. Then copy the following code to the, /path/to/codeigniter/application/models/shop_model.php file:
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'),
    
    class Shop_model extends CI_Model {
    
        function __construct() {
            parent::__construct();
            $this->load->helper('url'),
        }
    
        public function get_product_details($product_id) {
            $this->db->where('product_id', $product_id);
            $query = $this->db->get('products'),
            return $query;
        }
    
        public function get_all_products() {
            $query = $this->db->get('products'),
            return $query;
        }
    }
  3. Then copy the following code to the, path/to/codeigniter/application/views/shop/display_cart.php file:
    <?php echo form_open('shop/update_cart'), ?>
    
    <table cellpadding="6" cellspacing="1" style="width:50%" border="1">
    
      <tr>
        <th>Quantity</th>
        <th>Description</th>
        <th>Item Price</th>
        <th>Sub-Total</th>
      </tr>
    
      <?php $i = 1; ?>
    
      <?php foreach ($this->cart->contents() as $items): ?>
    
        <?php echo form_hidden($i . '[rowid]', $items['rowid']); ?>
    
        <tr>
          <td><?php echo form_input(array('name' => $i . '[qty]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?></td>
          <td>
            <?php echo $items['name']; ?>
    
            <?php if ($this->cart->has_options($items['rowid']) == TRUE): ?>
    
              <p>
                <?php foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
    
                  <strong><?php echo $option_name; ?>:</strong> <?php echo $option_value; ?><br/>
    
                <?php endforeach; ?>
              </p>
    
            <?php endif; ?>
    
          </td>
          <td><?php echo $this->cart->format_number($items['price']); ?></td>
          <td>$<?php echo $this->cart->format_number($items['subtotal']); ?></td>
        </tr>
    
        <?php $i++; ?>
    
      <?php endforeach; ?>
    
      <tr>
        <td colspan="2"> </td>
        <td><strong>Total</strong></td>
        <td>$<?php echo $this->cart->format_number($this->cart->total()); ?></td>
      </tr>
    
    </table>
    
    <p><?php echo form_submit('', 'Update Cart'), ?></p>
    <?php echo form_close() ; ?>
  4. Finally, copy the following code to the, path/to/codeigniter/application/views/shop/display_products.php file:
    <body>
        <table>
        <?php foreach ($query->result() as $row) : ?>
            <tr>
            <td><?php echo $row->product_id ; ?></td>
            <td><?php echo $row->product_name ; ?></td>
            <td><?php echo $row->product_description ; ?></td>
            <td><?php echo anchor('shop/add/'.$row->product_id, 'Add to cart') ; ?></td>
            </tr>
        <?php endforeach ; ?>
        </table>
    </body>

How it works...

Okay, there's a lot going on here; so rather than discussing what's going on in each file, we'll break it down into user actions. There are several actions users can perform when interacting with the cart. The most common are as follows:

  • User browses the catalogue
  • User adds an item to the cart
  • User updates or removes items in the cart

User browses the catalogue

public function index() in controllers/shop.php loads all the products from the database by calling the $this->Cart_model->get_all_products() function from Shop_model, and passes it to the, views/shop/display_products.php view, via $this->load->view('shop/display_products', $data).

User adds an item to the cart

User clicks on the Add to cart link in the, views/shop/display_products.php file, next to the item they wish to purchase, which calls public function add() in controllers/shop.php. public function add() fetches the product ID passed to it in the URL by $this->uri->segment(3) . Using this, $product_id looks up the product details from the database by $this->Shop_model->get_product_details($product_id). This data is then written to the cart by $this->cart->insert($data). Finally, the user is redirected to the cart with $this->load->view('shop/display_cart', $data) so they can view their item in the cart and make any amendments if they wish to.

User updates or removes items in the cart

This covers two actions: adding more items to the cart or completely removing an item or all items from the cart. They are described as follows:

  • Adding to or subtracting items from the cart: When the user views their cart, he they see a table with the quantities of each item in their cart to the left. The user can change the quantity of items by changing the values in this textbox. If the user increases or decreases the current quantity of a particular item and presses the, Update Cart button, then we run the shop controller function, update_cart(). update_cart() loops through the post array looking at each item and its new or desired quantity. It will track each item with the rowed value in the $data array, ensuring that the correct item is updated with the correct new quantity.
  • Removing items from the cart: This functions the same way as adding or removing items as previously described. However, the difference is that if the quantity chosen by the user is 0 (zero), then CodeIgniter will remove the item completely from the cart.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75