Added possibility to have multiple cart instances

This commit is contained in:
Rob Gloudemans
2013-05-28 22:26:25 +02:00
parent e727682446
commit c6473310d2
2 changed files with 65 additions and 2 deletions

View File

@@ -11,6 +11,13 @@ class Cart {
*/
protected $session;
/**
* Current cart instance
*
* @var string
*/
protected $instance;
/**
* Constructor
*
@@ -19,6 +26,22 @@ class Cart {
public function __construct($session)
{
$this->session = $session;
$this->instance = 'main';
}
/**
* Set the current cart instance
*
* @param string $instance Cart instance name
* @return Cart
*/
public function instance($instance)
{
$this->instance = $instance;
// Return self so the method is chainable
return $this;
}
/**
@@ -184,7 +207,7 @@ class Cart {
*/
protected function updateCart($cart)
{
return $this->session->put('cart', $cart);
return $this->session->put($this->getInstance(), $cart);
}
/**
@@ -194,11 +217,21 @@ class Cart {
*/
protected function getContent()
{
$content = ($this->session->has('cart')) ? $this->session->get('cart') : new CartCollection;
$content = ($this->session->has($this->getInstance())) ? $this->session->get($this->getInstance()) : new CartCollection;
return $content;
}
/**
* Get the current cart instance
*
* @return string
*/
protected function getInstance()
{
return 'cart.' . $this->instance;
}
/**
* Update a row if the rowId already exists
*

View File

@@ -123,4 +123,34 @@ class CartTest extends TestCase {
$this->assertEquals($count, 3);
}
public function testCartCanHaveMultipleInstances()
{
Cart::instance('test_1')->add(1, 'test_1', 1, 10.00, ['size' => 'L']);
Cart::instance('test_2')->add(2, 'test_2', 2, 10.00, ['size' => 'L']);
$name = Cart::instance('test_1')->content()->first()->name;
$this->assertEquals($name, 'test_1');
$name = Cart::instance('test_2')->content()->first()->name;
$this->assertEquals($name, 'test_2');
$count = Cart::count();
$this->assertEquals($count, 2);
Cart::add(3, 'test_3', 3, 10.00);
$count = Cart::count();
$this->assertEquals($count, 5);
Cart::instance('test_1')->add(1, 'test_1', 1, 10.00, ['size' => 'L']);
$count = Cart::count();
$this->assertEquals($count, 2);
}
}