Added a new associate method, to associate a row in the cart with a model, so you can access the model from the CartRowCollection

This commit is contained in:
Rob Gloudemans
2014-03-02 13:43:11 +01:00
parent 30d789f0c0
commit 47da5b128d
8 changed files with 159 additions and 7 deletions

View File

@@ -25,6 +25,20 @@ class Cart {
*/
protected $instance;
/**
* The Eloquent model a cart is associated with
*
* @var string
*/
protected $associatedModel;
/**
* An optional namespace for the associated model
*
* @var string
*/
protected $associatedModelNamespace;
/**
* Constructor
*
@@ -55,6 +69,24 @@ class Cart {
return $this;
}
/**
* Set the associated model
*
* @param string $modelName The name of the model
* @param string $modelNamespace The namespace of the model
* @return void
*/
public function associate($modelName, $modelNamespace = null)
{
$this->associatedModel = $modelName;
$this->associatedModelNamespace = $modelNamespace;
if( ! class_exists($modelNamespace . '\\' . $modelName)) throw new Exceptions\ShoppingcartUnknownModelException;
// Return self so the method is chainable
return $this;
}
/**
* Add a row to the cart
*
@@ -411,7 +443,7 @@ class Cart {
'price' => $price,
'options' => new CartRowOptionsCollection($options),
'subtotal' => $qty * $price
));
), $this->associatedModel, $this->associatedModelNamespace);
$cart->put($rowId, $newRow);
@@ -428,7 +460,6 @@ class Cart {
protected function updateQty($rowId, $qty)
{
if($qty <= 0)
if($qty == 0)
{
return $this->remove($rowId);
}

View File

@@ -4,9 +4,33 @@ use Illuminate\Support\Collection;
class CartRowCollection extends Collection {
public function __construct($items)
/**
* The Eloquent model a cart is associated with
*
* @var string
*/
protected $associatedModel;
/**
* An optional namespace for the associated model
*
* @var string
*/
protected $associatedModelNamespace;
/**
* Constructor for the CartRowCollection
*
* @param array $items
* @param string $associatedModel
* @param string $associatedModelNamespace
*/
public function __construct($items, $associatedModel, $associatedModelNamespace)
{
parent::__construct($items);
$this->associatedModel = $associatedModel;
$this->associatedModelNamespace = $associatedModelNamespace;
}
public function __get($arg)
@@ -16,10 +40,18 @@ class CartRowCollection extends Collection {
return $this->get($arg);
}
return NULL;
if($arg == strtolower($this->associatedModel))
{
$modelInstance = $this->associatedModelNamespace ? $this->associatedModelNamespace . '\\' .$this->associatedModel : $this->associatedModel;
$model = new $modelInstance;
return $model->find($this->id);
}
return null;
}
public function search(Array $search)
public function search(array $search)
{
foreach($search as $key => $value)
{

View File

@@ -0,0 +1,3 @@
<?php namespace Gloudemans\Shoppingcart\Exceptions;
class ShoppingcartUnknownModelException extends \Exception {}