[eluser]ontguy[/eluser]
This is what I've done, I'm not sure how elegant it is
I haven't gone beyond the shopping cart as yet, so my approach may change.
Let me know what you think.
The cart holds a 2D array with the product id as the key:
Array ( [15] => Array ( [quantity] => 1 ) [6] => Array ( [quantity] => 1 ) [8] => Array ( [quantity] => 1 ) )
Only quantity is tracked but it's easy to add other details if needed.
Here is the jist of it:
application/libraries/Cart_lib.php
Code:
function get_cart()
{
return $this->CI->session->userdata('cart');
}
function set_cart($param)
{
return $this->CI->session->set_userdata('cart', $param);
}
function add_item($product_id, $quantity = 1)
{
$items = $this->get_cart();
if (!$items)
{
$item = array($product_id => array(
'quantity' => $quantity,)
);
$this->set_cart($item);
}
else
{
if (isset($items[$product_id]))
{
$items[$product_id]['quantity'] += $quantity;
}
else
{
$items += array($product_id => array(
'quantity' => $quantity,)
);
}
$this->set_cart($items);
}
}
function edit_item($product_id = 0, $quantity = 0)
{
if($quantity < 1)
{
$this->delete_item($product_id);
}
else
{
$items = $this->get_cart();
$items[$product_id]['quantity'] = $quantity;
$this->set_cart($items);
}
}
function delete_item($item_id = 0)
{
$items = $this->get_cart();
$new_cart = array();
foreach($items as $product_id => $product)
{
if($product_id != $item_id)
{
$new_cart += array($product_id => array(
'quantity' => $product['quantity'],)
);
}
}
$this->set_cart($new_cart);
}
how the library is used in the controller:
application/controllers/cart.php
Code:
function view()
{
$this->data->cart = $this->cart_lib->cart_details();
$this->data->total = $this->cart_lib->cart_total;
$this->loadview('cart/view', $this->data);
}
function add()
{
$product_id = (int) $this->uri->segment(3);
$this->cart_lib->add_item($product_id);
redirect('catalog');
}
function delete()
{
$product_id = (int) $this->uri->segment(3);
if ($product_id != 0)
{
$this->cart_lib->delete_item($product_id);
redirect('cart/view');
}
else
{
$this->view();
}
}
function update()
{
foreach($_POST as $key => $value)
{
if (stristr($key,'quantity'))
{
$id = str_replace('quantity','',$key);
if(preg_match( '/^[\-+]?[0-9]+$/', $value))
{
$this->cart_lib->edit_item($id, $value);
}
else
{
$this->messages->add('The quantity field must contain an integer.', 'error');
}
}
}
redirect('cart/view');
}
the view would have something like this to utilize the cart controller:
application/views/catalog/browse.php
Code:
<?=anchor('cart/add/'.$row->id, 'Add To Cart'); ?>