diff --git a/src/Gloudemans/Shoppingcart/Cart.php b/src/Gloudemans/Shoppingcart/Cart.php index 13e33cc..08c56cd 100644 --- a/src/Gloudemans/Shoppingcart/Cart.php +++ b/src/Gloudemans/Shoppingcart/Cart.php @@ -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 * diff --git a/tests/CartTest.php b/tests/CartTest.php index 5872764..ec4d6d4 100644 --- a/tests/CartTest.php +++ b/tests/CartTest.php @@ -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); + } + } \ No newline at end of file