shopping cart (MVC): the time when an item is added

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

shopping cart (MVC): the time when an item is added

Post by lauthiamkok »

Hi,

I am using MVC concept to create a basic shopping cart for learning purposes, I have no problem adding/ deleting/ updating items in my cart, but I want to add the timestamp when an item is created into my cart, I still cannot think of a proper method I can achieve this...

It would be wonderful if you have any ideas!

Below is the codes.

This is the code call the cart controller,

Code: Select all

#includes the configuration
require_once('inc/global.inc.php');

#includes classes into the application
require ('class_lib.php');

#starts the session
session_start();

$cart_controller = new __cart_controller();
$cart_controller -> invoke_cart($template = 'view.php');
This is the classes of cart, product (model, controller, entity),

Code: Select all

/**
 * this file handles the retrieval and serving of page
 */ 
class __cart_controller 
{
	private $cart_model;
	
	public function __construct()  
    {  
        $this -> cart_model = new __cart_model();
    } 
	
	public function invoke_cart($template)
	{	
		#presets the variables
		$action = null;

		if(isset($_GET['action'])) $action = $_GET['action'];
		
		#invoke the __cart_model class, assigning the object to a session variable
		if (!isset($_SESSION[CART]))
		{
			$cart =  $this -> cart_model;
		}
		else 
		{
			$cart = unserialize($_SESSION[CART]);
		}
		
		#proccessing the item in the cart
		if($action == 'update')
		{
			foreach ($_POST as $key => $value) 
			{
				#updates the qunatity of an item
				$cart -> update_quantity($key,$value);	
			}
			
			#always place this line below the method of add_item, of delete_item, and update_quantity
			$_SESSION[CART] = serialize($cart);	
				
			#get the main template
			include $template;
		}
		
		elseif($action == 'delete')
		{
			#removes a product from the cart
			$cart -> delete_item($_REQUEST['pro_id']);
			
			#always place this line below the method of add_item, of delete_item, and update_quantity
			$_SESSION[CART] = serialize($cart);	
			
			#get the main template
			include $template;
		}
		
		else
		{
			#adds a product to the cart
			$cart -> add_item($_REQUEST['pro_id']);
			//$cart -> add_item($_REQUEST['pro_id'],$time = time());
			
			#always place this line below the method of add_item, of delete_item, and update_quantity
			$_SESSION[CART] = serialize($cart);	
			
			print_r($cart);
			
			#get the main template
			include $template;
			
			/*
			* for checking purposes only :-
			*
			*
			
			#make the cart an array to store multiple items.
			$cart2 = array();

			#make the cart store the session.
			$cart2 = $_SESSION['cart_1'];

			#store the item in array.
			$cart2[] = $_GET['pro_id'];

			#make the designated session remember previous items otherwise each new session will replace the previous one.
			$_SESSION['cart_1'] = $cart2;

			#for instance, Array ( [0] => 2 [1] => 3 [2] => 4 ) .
			print_r($cart2);
			
			#put the cart into condiction.
			if (!isset($_SESSION['cart2']))
				{
				$cart2 = array();
				}
			else
				{
				$cart2 = $_SESSION['cart2'];
				}
			
			$cart2[$_REQUEST['pro_id']] = array();			
			$cart2[$_REQUEST['pro_id']]['id'] = $_REQUEST['pro_id'];
			$cart2[$_REQUEST['pro_id']]['created'] = time();
			$_SESSION['cart2'] = $cart2;

			print_r($cart2);
			*
			*
			*/
		}
	}
}

/**
* The store model.
*
*/
class __store_model 
{ 
    /**
	 * holds instance of database connection
	 */
	protected $database;
		
	public function __construct()
	{
		$this -> database = new __database(DB_HOST,DB_USER,DB_PASS,DB_NAME);
	} 

    public function get_store() 
    { 
        #prepare the query
		$sql = "
		SELECT * FROM root_products
		
		LEFT JOIN root_pages
		ON root_products.pg_id = root_pages.pg_id
			
		ORDER BY root_pages.pg_created
		";
	   
		#execute the query	and store the array in the variale
		$product = $this->database->fetch_all($sql);	

		#return the result
		return $product;
    } 
}

/**
* The product model.
*
*/
class __product_model extends __store_model
{ 
    public function get_product($pro_id) 
    { 
        #prepare the query
		$sql = "
		SELECT * FROM root_products
		
		LEFT JOIN root_pages
		ON root_products.pg_id = root_pages.pg_id
			
		WHERE root_products.pro_id = '".$pro_id."'
		";
	   
		#execute the query	and store the array in the variale
		$product = $this->database->fetch_assoc($sql);
		
		#send it to the entity class and instantiate an object from it
		$product = new __product_entity($product);
		
		#return the result
		return $product;
    } 
}

/**
* The product entity.
*
*/
class __product_entity 
{
	public $pro_id = null;
	public $pro_title = null;
	public $pro_price = null;
	
	/**
	 * fetch the array and keep the data in varibales
	 * @param string $page
	 */
	public function __construct($product)  
    {  
       
		$this->pro_id = $product['pro_id'];
		$this->pro_title = $product['pg_title'];
		$this->pro_price = $product['pro_price_primary'];
		
		//print_r($product);
    } 
}

/**
* The shopping cart.
*
*/
class __cart_model
{
	 private $content = array();
	 private $created;
	 /**
	  * The class constructor
	  *
	  */
	 public function __construct() 
	 {
         $this->created = time();
	 }
	 
	 /**
	  * Add a product to the cart
	  * @access public
	  * @param $pro_id integer
	  *
	  */
	//public function add_item($pro_id,$time) 
	public function add_item($pro_id) 
	{
	 	if (isset($this->content[$pro_id])) 
		{
	 	    $this->content[$pro_id]++;
			
			/*$this->content[$pro_id] = array();
			$this->content[$pro_id]['q'] = $this->content[$pro_id]['q'] + 1;
			$this->content[$pro_id]['t'] = $time;
			*/
	 	} 
		else 
		{
	 		$this->content[$pro_id] = 1;
			
			/*
			$this->content[$pro_id] = array();
			$this->content[$pro_id]['q'] = 1;
			$this->content[$pro_id]['t'] = $time;
			echo $time;
			*/
			
	 	}
		//print_r($this->content);
	}
	 
	 /**
	  * Remove product from cart
	  * @access public
	  * @param $pro_id integer
	  *
	  */
	public function delete_item($pro_id) 
	{	
 		if (isset($this->content[$pro_id])) 
		{
 			unset($this->content[$pro_id]);
 		} 		
	}
	 
	 /**
	  * Change the quantity of a particular item held in the shopping cart
	  *
	  * @access public
	  * @param integer $pro_id
	  * @param integer $quantity
	  */
	public function update_quantity($pro_id, $quantity) 
	{
	 	$this->content[$pro_id] = $quantity;
	}
	 
	 /**
	  * Get all items currently in cart
	  *
	  * @access public
	  * @return unknown
	  */
	public function get_items() 
	{
	 	return $this->content;
	}
	 
	 /**
	  * How many items are in the user's cart?
	  * 
	  * @access public
	  * @return INTEGER
	  *
	  */
	public function count_items() 
	{
	 	return array_sum($this->content);
	}

	 /**
	  * Calculate the cost of all items in the cart
	  * @access public
	  * @return float
	  *
	  */
	public function calculate_cost() 
	{ 	
	 	$cost = 0.00;
	 	
	 	foreach($this->content AS $pro_id => $quantity) 
		{	
	 		//$cost = $cost + ($product -> price * $quantity);
			
			# Instantiate the object from the class.
			$product = new __product_model();

			# Pass the parameter and access the method in the class.
			$product = $product->get_product($pro_id);
			
			# Calculate the total cost.
			$cost = $cost + ($product -> pro_price * $quantity);
	 	}
	 	
	 	return number_format($cost, 2);
		//return $cost_float; 	
	}	 
}
I have tried to create a multidimensional array to pass the function of time() into the class method of add_item(), as below, but it generate an error message when an previous item is already set in the session/ array.

Code: Select all

public function add_item($pro_id,$time) 
	{
	 	if (isset($this->content[$pro_id])) 
		{
	 	    
			//$this->content[$pro_id]++;
			$this->content[$pro_id] = array();
			$this->content[$pro_id]['q'] = $this->content[$pro_id]['q'] + 1;
			$this->content[$pro_id]['t'] = $time;
	 	} 
		else 
		{
	 		//$this->content[$pro_id] = 1;
			
			$this->content[$pro_id] = array();
			$this->content[$pro_id]['q'] = 1;
			$this->content[$pro_id]['t'] = $time;
			
	 	}
		//print_r($this->content);
	}
result:

Notice: Undefined index: q in C:\wamp\www\....

This is the live test site (without the error above) to show u what I intend to achieve,
http://lauthiamkok.net/tmp/php/cart/cart.php?pro_id=1

(note: you need to add the item by changing the value of pro_id from 1 to 4 so that u can see the shopping cart. bcos the index page won't work on this live site for some reason, with this line of code,

Code: Select all

$store = $object_store -> get_store();
but it works perfectly on my localhost!

this is the code to get the list of the items on the index page,

Code: Select all

<?php
$object_store = new __store_model();

$store = $object_store -> get_store();

foreach ($store as $product)
{
	$product = new __product_entity($product);
?>
	<li><?php echo $product -> pro_title;?> by <?php //echo $product -> pro_author;?>: &pound;<?php echo $product -> pro_price;?><br />
		<a href="cart.php?pro_id=<?php echo $product -> pro_id;?>">Add to cart</a>
	</li>

<?php
}

?>
)

Many thanks!

Lau
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: shopping cart (MVC): the time when an item is added

Post by andyhoneycutt »

Changes below ...

Code: Select all

// CHANGE THIS:
// public function add_item($pro_id,$time)
// TO THIS:
public funciton add_item($pro_id)
        {
                if (isset($this->content[$pro_id]))
                {
                   
                        //$this->content[$pro_id]++;
                        // REMOVE THIS ----> $this->content[$pro_id] = array();
                        // CHANGE THIS:
                        $this->content[$pro_id]['q']++;
                        // CHANGE BELOW:
                        $this->content[$pro_id]['t'] = time();
                }
                else
                {
                        //$this->content[$pro_id] = 1;
                        // CHANGE LINE BELOW:
                        $this->content[$pro_id] = array('q' => 1, 't' => time());
                        // REMOVE ====> $this->content[$pro_id]['q'] = 1;
                        // REMOVE ====> $this->content[$pro_id]['t'] = $time;
                       
                }
                //print_r($this->content);
        }
I think that should do it. You are re-initializing your array on an add_item where the $pro_id context already exists. Also, why change the add_item function, just call time() where needed.

Although, really, it looks like all you're going to end up with is when the last item was added with that product id. Not a historic of add times for each item, or I am misunderstanding the context of $pro_id.

-Andy
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: shopping cart (MVC): the time when an item is added

Post by AbraCadaver »

So you've been helped in 2 identical threads, how many more are there? viewtopic.php?f=1&t=117587
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: shopping cart (MVC): the time when an item is added

Post by andyhoneycutt »

:banghead:
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

Re: shopping cart (MVC): the time when an item is added

Post by lauthiamkok »

AbraCadaver wrote:So you've been helped in 2 identical threads, how many more are there? viewtopic.php?f=1&t=117587
oh sorry. i posted the same thread twice! :oops:
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

Re: shopping cart (MVC): the time when an item is added

Post by lauthiamkok »

andyhoneycutt wrote:
I think that should do it. You are re-initializing your array on an add_item where the $pro_id context already exists. Also, why change the add_item function, just call time() where needed.
thanks Andy!

Now I know why my multidimensional array wasn't working! I think I am a bit of dumb**s in programming!
andyhoneycutt wrote: Although, really, it looks like all you're going to end up with is when the last item was added with that product id. Not a historic of add times for each item, or I am misunderstanding the context of $pro_id.
yes it is not recording each item historically. bcos the same item (for instance, pro_id = 1) could have more than 1 in the quantity. Below is the array outcome,

Code: Select all

Array
(
    [1] => Array
        (
            [q] => 20
            [t] => 1276631850
        )

    [3] => Array
        (
            [q] => 22
            [t] => 1276631853
        )
u can see the the product id 1 has 20 amount in the quantity. and I only record the last item of this product id.

hope this is making sense! :?

thanks for your help!
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: shopping cart (MVC): the time when an item is added

Post by andyhoneycutt »

Awesomesauce! Glad this is working for you now :)
lauthiamkok
Forum Contributor
Posts: 153
Joined: Wed Apr 01, 2009 2:23 pm
Location: Plymouth, United Kingdom

Re: shopping cart (MVC): the time when an item is added

Post by lauthiamkok »

:drunk: :mrgreen:
Post Reply