PHP Classes

File: dcart.php

Recommend this page to a friend!
  Classes of Dhiman Chakraborty   dcart   dcart.php   Download  
File: dcart.php
Role: Class source
Content type: text/plain
Description: Shopping Cart class in PHP
Class: dcart
Manage shopping cart items stored in sessions
Author: By
Last change:
Date: 10 years ago
Size: 1,862 bytes
 

Contents

Class file image Download
<?php
/**
 * Class dCart
 * Description Shopping Cart System
 * @author Dhiman Chakraborty
 * @date May 30, 2013
 */

class dCart{
    protected static
$instance;
    protected
$items;
    protected
$sessionIndex;
   
    public function
dCart(){
       
$this->items = array();
       
$this->writeSession();
        return
$this;
    }
   
    public static function
getInstance($sessionIndex = 'cart'){
       
self::startSession();
        if(!isset(
$_SESSION[$sessionIndex])){
           
$_SESSION[$sessionIndex] = new self;
        }
        return
$_SESSION[$sessionIndex];
    }
   
    public static function
startSession(){
        if(
session_id() == '') {
           
session_start();
        }
    }
   
   
    protected function
writeSession(){
       
$_SESSION[$this->sessionIndex] = $this->items;
    }
   
    public function
Add($newOrder = array()){
       
$itemFound = false;
        foreach(
$this->items as $key=>$item){
            if((
$item['id'] == $newOrder['id']) && array_key_exists('quantity',$this->items[$key]) && array_key_exists('quantity',$newOrder)){
               
$this->items[$key]['quantity'] += $newOrder['quantity'];
               
$itemFound = true;
            }
        }
        if(!
$itemFound){
           
array_push($this->items,$newOrder);
        }
       
$this->writeSession();
        return
$this;
    }
    public function
Remove($key = NULL){
       
        if(
func_num_args() != 0){
            unset(
$this->items[$key]);
           
sort($this->items);
        }else{
           
$this->items = array();
        }
       
$this->writeSession();
        return
$this;
    }
   
    public function
Edit($key = NULL,$index = NULL, $value = array()){
        if(
array_key_exists($key,$this->items) && array_key_exists($index,$this->items[$key])){
           
$this->items[$key][$index] = $value;
        }
       
$this->writeSession();
        return
$this;
    }
   
    public function
Show(){
        echo
"<pre>";
       
print_r($this->items);
        echo
"</pre>";
        return
$this;
    }
    public function
GetAll(){
        return
$this->items;
    }
}