Shoppingcart 购物车

还是拿来主义编程思想,既然别人实现了,就不再造轮子了。

LaravelShoppingcart是Laravel下的一个购物车实现,项目地址:

https://github.com/Crinsane/LaravelShoppingcart

文档翻译:

针对Laravel 4的简单购物车实现。

安装

通过composer安装,编辑 composer.json 文件,如下:

Laravel4.2及以下

"require": {
"laravel/framework": "4.2.*",
"gloudemans/shoppingcart": "~1.2"
}

Laravel5

"require": {
"laravel/framework": "5.0.*",
"gloudemans/shoppingcart": "dev-master"
}

接着运行更新命令

composer update

添加以下代码到 app/config/app.phpservice providers 数组里

"GloudemansShoppingcartShoppingcartServiceProvider"

添加以下代码到aliases数组中

"Cart" => "GloudemansShoppingcartFacadesCart",

完成以上工作就可以在你的项目中使用了。

使用

Shoppingcart提供了以下的可用方法:

Cart:add()

/**
* Add a row to the cart
* 向购物车添加新行
*
* @param string|Array $id Unique ID of the item|Item formated as array|Array of items
* -参数 字符串|数组 $id item的唯一id | Item格式化成数组 | items 数组
* @param string $name Name of the item
* -参数 字符串 $name item 名称
* @param int $qty Item qty to add to the cart
* -param int $qty 添加到购物车的item的数量
* @param float $price Price of one item
* -param float $price item 价格
* @param Array $options Array of additional options, such as "size" or "color"
* @param Array $options 附加参数数组, 诸如"size" 或 "color"
*/

// Basic form 基础表单
Cart::add("293ad", "Product 1", 1, 9.99, array("size" => "large"));

// Array form 数组表单
Cart::add(array("id" => "293ad", "name" => "Product 1", "qty" => 1, "price" => 9.99, "options" => array("size" => "large")));

// Batch method 批量方法
Cart::add(array(
array("id" => "293ad", "name" => "Product 1", "qty" => 1, "price" => 10.00),
array("id" => "4832k", "name" => "Product 2", "qty" => 1, "price" => 10.00, "options" => array("size" => "large"))
));

Cart:update()

/**
* Update the quantity of one row of the cart
*
* @param string $rowId The rowid of the item you want to update
* @param integer|Array $attribute New quantity of the item|Array of attributes to update
* @return boolean
*/
$rowId = "da39a3ee5e6b4b0d3255bfef95601890afd80709";

Cart::update($rowId, 2);

OR

Cart::update($rowId, array("name" => "Product 1"));

Cart::remove()

/**
* Remove a row from the cart
*
* @param string $rowId The rowid of the item
* @return boolean
*/

$rowId = "da39a3ee5e6b4b0d3255bfef95601890afd80709";

Cart::remove($rowId);

Cart::get()

/**
* Get a row of the cart by its ID
*
* @param string $rowId The ID of the row to fetch
* @return CartRowCollection
*/

$rowId = "da39a3ee5e6b4b0d3255bfef95601890afd80709";

Cart::get($rowId);

Cart::content()

/**
* Get the cart content
*
* @return CartCollection
*/

Cart::content();

Cart::destroy()

/**
* Empty the cart 清空购物车
*
* @return boolean
*/
Cart::destroy();

Cart:total()

/**
* Get the price total 获取总价格
*
* @return float
*/
Cart::total();

Cart:count()

/**
* Get the number of items in the cart
*
* @param boolean $totalItems Get all the items (when false, will return the number of rows)
* @return int
*/
Cart::count(); // Total items
Cart::count(false); // Total rows

Cart::search()

/**
* Search if the cart has a item
*
* @param Array $search An array with the item ID and optional options
* @return Array|boolean
*/
Cart::search(array("id" => 1, "options" => array("size" => "L"))); // Returns an array of rowid(s) of found item(s) or false on failure

Collections

显而易见,Cart::content()Cart::get()返回一个集合,CartCollectionCartRowCollection

这些集合扩展了原始的Laravel 4collection类,所以这个类的所有方法同样的可以被使用在购物车类中。

实例

现在扩展包可以支持多个购物车实例,工作方式像这样:

你可以使用Cart::instance(‘newInstance’)设置当前的购物车实例,此刻,有效的购物车实例是newInstance,所以你添加、移除或获取购物车内容,操作的都是newInstance。如果你需要选择其它实例,你只需要调用Cart::instance(‘otherInstance’)

Cart::instance("shopping")->add("192ao12", "Product 1", 1, 9.99);
// Get the content of the "shopping" cart
Cart::content();
Cart::instance("wishlist")->add("sdjk922", "Product 2", 1, 19.95, array("size" => "medium"));
// Get the content of the "wishlist" cart
Cart::content();
// If you want to get the content of the "shopping" cart again...
Cart::instance("shopping")->content();
// And the count of the "wishlist" cart again
Cart::instance("wishlist")->count();

备注1:如果你不重新设置,购物车永远是最后一个实例

备注2:默认的购物车实例名称是mian,所以Cart::content();等同于Cart::instance(‘main’)->content()。

Models

一个新特性是可以使为购物车的item关联一个模型。假设在你的应用中有一个product模型,通过新的associate()方法,可以通知购物车里的项关联到product模型。

这样你可以从 CartRowCollection 访问你的模型。

下面是一个示例:

<?php

/**
* Let say we have a Product model that has a name and description.
*/

Cart::associate("Product")->add("293ad", "Product 1", 1, 9.99, array("size" => "large"));
$content = Cart::content();
foreach($content as $row)
{
echo "You have " . $row->qty . " items of " . $row->product->name . " with description: "" . $row->product->description . "" in your cart.";
}

访问模型的主键和关联模型的名称相同。associate()还有第二个参数,是可选的,用于指定模型的命名空间。

异常错误

当发生错误时,购物车模块将抛出异常。使用购物车模块可以很容易的调试错误,或者基于异常的类型处理错误。购物车模块可以抛出以下异常:

ExceptionReason
ShoppingcartInstanceExceptionWhen no instance is passed to the instance() method 没有实例传递给instance()方法
ShoppingcartInvalidItemExceptionWhen a new product misses one of it’s arguments (id,name, qty, price) 当新产品缺少一个参数
ShoppingcartInvalidPriceExceptionWhen a non-numeric price is passed当非数值的价格被传递
ShoppingcartInvalidQtyExceptionWhen a non-numeric quantity is passed当非数值的数量被传递
ShoppingcartInvalidRowIDExceptionWhen the $rowId that got passed doesn’t exists in the current cart当当前的购物车并不存在被传来的$roeid
ShoppingcartUnknownModelExceptionWhen an unknown model is associated to a cart row当一个未知的模型被关联到购物车的行

Events

下面是购物车监听的事件:

EventFired
cart.add($item)When a single item is added当单个item被添加
cart.batch($items)When a batch of items is added当一批item被添加
cart.update($rowId)When an item in the cart is updated购物车单个item跟更新
cart.remove($rowId)When an item is removed from the cart当一个item被从购物车中移除
cart.destroy()When the cart is destroyed当购物车被清空

示例:

下面的示例展示了如果在table中呈现购物车的内容

// Controller

Cart::add("192ao12", "Product 1", 1, 9.99);
Cart::add("1239ad0", "Product 2", 2, 5.95, array("size" => "large"));

// View

<table>
<thead>
<tr>
<th>Product</th>
<th>Qty</th>
<th>Item Price</th>
<th>Subtotal</th>
</tr>
</thead>

<tbody>

<?php foreach($cart as $row) :?>

<tr>
<td>
<p><strong><?php echo $row->name;?></strong></p>
<p><?php echo ($row->options->has("size") ? $row->options->size : "");?></p>
</td>
<td><input type="text" value="<?php echo $row->qty;?>"></td>
<td>$<?php echo $row->price;?></td>
<td>$<?php echo $row->subtotal;?></td>
</tr>

<?php endforeach;?>

</tbody>
</table>

原文地址:http://www.zhangxihai.cn/archives/189

文章导航