jackiedo/shoppingcart

此包已被弃用且不再维护。作者建议使用 jackiedo/cart 包代替。

用于在 Laravel 中创建购物车的轻量级包

1.0.2 2017-05-16 06:45 UTC

This package is auto-updated.

Last update: 2022-02-01 12:52:45 UTC


README

一个用于在 Laravel 应用程序中创建购物车的轻量级包。(现在仅支持 Laravel 4.x)

弃用公告

此包已被弃用。请使用同一发布者的 Laravel-Cart 包作为替代。

概述

查看以下主题以了解更多关于 LaravelShoppingCart 的信息:

安装

您可以通过 Composer 安装此包。

  • 首先,编辑您项目的 composer.json 文件,以添加 jackiedo/shoppingcart 依赖。
...
"require": {
    ...
    "jackiedo/shoppingcart": "1.*"
},
  • 然后,在终端中更新 Composer。
$ composer update
  • 更新操作完成后,第三步是添加服务提供者。打开 app/config/app.php,并在 providers 数组中添加一个新项
...
'providers' => array(
    ...
    'Jackiedo\Shoppingcart\ShoopingcartServiceProvider',
),

最后一步是在 aliases 部分添加以下行

'Cart'      => 'Jackiedo\Shoppingcart\Facades\Cart',

使用

添加商品到购物车

添加一个新的商品。

/**
 * Add a new item to the cart
 *
 * @param string|int    $id       ID of the item (such as product's id)
 * @param string        $title    Name of the item
 * @param int           $qty      Item qty to add to the cart
 * @param float         $price    Price of one item
 * @param array         $options  Array of additional options, such as 'size' or 'color'
 * @return Jackiedo\Shoppingcart\CartItem|null
 */
Cart::add( $id, $title, $quantity, $price [, $options = array()] );

示例

$row = Cart::add(37, 'Item Title', 5, 100.00, ['color' => 'red', 'size' => 'M']);

// Collection CartItem: {
//    rawId    : '8a48aa7c8e5202841ddaf767bb4d10da'
//    id       : 37
//    title    : 'Item Title'
//    qty      : 5
//    price    : 100.00
//    subtotal : 500.00
//    options  : Collection CartItemOptions: {
//                      color : 'red'
//                      size  : 'M'
//                  }
// }

$rawId = $row->rawId(); // get rawId (8a48aa7c8e5202841ddaf767bb4d10da)
$rowQty = $row->qty; // 5
...

更新商品

更新指定的商品。

/**
 * Update the quantity of one row of the cart
 *
 * @param  string       $rawId       The rawId of the item you want to update
 * @param  int|array    $attribute   New quantity of the item|Array of attributes to update
 * @return Jackiedo\Shoppingcart\CartItem
 */
Cart::update(string $rawId, int $quantity);
Cart::update(string $rawId, array $arrtibutes);

示例

$rawId = '8a48aa7c8e5202841ddaf767bb4d10da';

// Update title and options
$row = Cart::update($rawId, ['title' => 'New item name', 'options' => ['color' => 'yellow']]);

// or only update quantity
$row = Cart::update($rawId, 5);

获取所有商品

获取所有商品。

/**
 * Get the cart content
 *
 * @return \Illuminate\Support\Collection
 */
Cart::all();
// or use alias
Cart::content();

示例

$items = Cart::content();

// Collection $items: {
//     8a48aa7c8e5202841ddaf767bb4d10da: {
//         rawId: '8a48aa7c8e5202841ddaf767bb4d10da',
//         id: 37,
//         title: 'New item name',
//         qty: 5,
//         price: 100.00,
//         subtotal: 500.00,
//         options: {
//             'color': 'yellow',
//             'size': 'M'
//         }
//     },
//     4c48ajh68e5202841ed52767bb4d10fc: {
//         rawId: '4c48ajh68e5202841ed52767bb4d10fc',
//         id: 42,
//         title: 'Men T-Shirt Apolo',
//         qty: 1,
//         price: 1000.00,
//         subtotal: 1000.00,
//         options: {
//             'color': 'red',
//             'size': 'L'
//         }
//     }
//     ...
// }

获取商品

获取指定的商品。

/**
 * Get a row of the cart by its unique ID
 *
 * @param  string  $rawId  The ID of the row to fetch
 * @return Jackiedo\Shoppingcart\CartItem
 */
Cart::get(string $rawId);

示例

$item = Cart::get('8a48aa7c8e5202841ddaf767bb4d10da');

// Collection $item: {
//    rawId    : '8a48aa7c8e5202841ddaf767bb4d10da'
//    id       : 37
//    title    : 'Item Title'
//    qty      : 5
//    price    : 100.00
//    subtotal : 500.00
//    options  : {
//        'color'   : 'red',
//        'size'    : 'M'
//    }
// }

移除商品

通过原始 ID 移除指定的商品。

/**
 * Remove a row from the cart
 *
 * @param  string  $rawId  The unique ID of the item
 * @return boolean
 */
Cart::remove(string $rawId);

示例

Cart::remove('8a48aa7c8e5202841ddaf767bb4d10da');

销毁购物车

清理购物车。

/**
 * Empty the cart
 *
 * @return boolean
 */
Cart::destroy();

示例

Cart::destroy();

获取总价

返回所有商品的总价。

/**
 * Get the price total
 *
 * @return float
 */
Cart::total();

示例

$total = Cart::total();

行数统计

返回行数。

/**
 * 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(false);
// or use alias
Cart::countRows();

示例

Cart::add(37, 'Item name', 5, 100.00, ['color' => 'red', 'size' => 'M']);
Cart::add(37, 'Item name', 1, 100.00, ['color' => 'red', 'size' => 'M']);
Cart::add(37, 'Item name', 5, 100.00, ['color' => 'red', 'size' => 'M']);
Cart::add(127, 'foobar', 15, 100.00, ['color' => 'green', 'size' => 'S']);
$rows = Cart::countRows(); // 2

数量统计

返回所有商品的数量

/**
 * 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($totalItems = true);

$totalItems : 当 false 时,返回行数。

示例

Cart::add(37, 'Item name', 5, 100.00, ['color' => 'red', 'size' => 'M']);
Cart::add(37, 'Item name', 1, 100.00, ['color' => 'red', 'size' => 'M']);
Cart::add(37, 'Item name', 5, 100.00, ['color' => 'red', 'size' => 'M']);
$count = Cart::count(); // 11 (5+1+5)

搜索商品

通过属性搜索商品。

/**
 * Search if the cart has a item
 *
 * @param  array  $search  An array with the item ID and optional options
 * @return Illuminate\Support\Collection;
 */
Cart::search(array $conditions);

示例

$items = Cart::search(['options' => ['color' => 'red']]);
$items = Cart::search(['title' => 'Item name']);
$items = Cart::search(['id' => 10, 'options' => ['size' => 'L']]);

集合

如您所见,有两种方法和一个属性都返回 Collection。这些是 Cart::content() (Cart)Cart::get() (CartItem)Cart::get()->options (CartItemOptions)

这些集合扩展了 'native' Laravel 集合类,因此您可以从集合类中使用的所有方法也可以用于您的购物车。通过一些添加,可以轻松地处理购物车的内容。

实例

现在该包也支持购物车的多个实例。其工作方式如下

您可以使用 Cart::instance('newInstance') 设置当前购物车实例,此时,活动的购物车实例是 newInstance,因此当您添加、删除或获取购物车的内容时,您将使用购物车的 newInstance 实例。

如果您想切换实例,只需再次调用 Cart::instance('otherInstance'),您将再次使用 otherInstance

以下是一个小例子

Cart::instance('shopping')->add('37', 'Product 1', 1, 9.99);

// Get the content of the 'shopping' cart
Cart::content();

Cart::instance('wishlist')->add('42', '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();

注意

  • 请记住,只要在脚本执行期间不设置不同的实例,购物车就会保留在最后一个设置的实例中。

  • 默认的购物车实例名为 main,因此当您不使用实例时,Cart::content();Cart::instance('main')->content() 相同

模型

一个特殊的功能是将模型与购物车中的项目关联起来。比如说,您在应用程序中有一个 Product 模型。使用新的 associate() 方法,您可以告诉购物车购物车中的一个项目与 Product 模型相关联。这样,您就可以直接从 CartItem 访问您的模型了!

/**
 * Set the associated model
 *
 * @param  string    $modelName        The name of the model
 * @param  string    $modelNamespace   The namespace of the model
 * @return Jackiedo\Shoppingcart\Cart
 */
Cart::associate(string $modelName, string $modelNamespace = null);

示例

Cart::associate('ShoppingProduct', 'App\Models');
$item = Cart::get('8a48aa7c8e5202841ddaf767bb4d10da');
$item->shopping_product->title; // $item->shopping_product is instance of 'App\Models\ShoppingProduct'

访问模型的关键字是与您关联的模型名称的蛇形名称(例如:模型名称是 ShoppingProduct,则关键字是 shopping_product)。associate() 方法有一个第二个可选参数,用于指定模型命名空间。

异常

如果出现错误,购物车包将抛出异常。这样,使用购物车包调试代码或根据异常类型处理错误就更容易了。购物车包可以抛出以下异常

异常 原因
ShoppingcartInvalidItemException 当一个新产品缺少 id 或标题参数(idtitle)时
ShoppingcartInvalidPriceException 当一个非数字或负数的价格被传递时
ShoppingcartInvalidQtyException 当一个非数字或小于 1 的数量被传递时
ShoppingcartInvalidRawIDException 当传递的 $rawId 在当前购物车中不存在时
ShoppingcartUnknownModelException 当一个未知模型与购物车行相关联时

事件

事件名称 参数
cart.adding ($attributes, $cart);
cart.added ($attributes, $cart);
cart.updating ($row, $cart);
cart.updated ($row, $cart);
cart.removing ($row, $cart);
cart.removed ($row, $cart);
cart.destroying ($cart);
cart.destroyed ($cart);

您可以轻松处理这些事件,例如

Event::on('cart.adding', function($attributes, $cart){
    // code
});

许可

MIT

感谢使用

希望,这个包对您有用。