frezno/freznocart

Laravel 5 购物车

此软件包的官方仓库似乎已消失,因此该软件包已被冻结。

v2.5.0 2017-03-11 17:19 UTC

This package is not auto-updated.

Last update: 2020-06-12 20:10:33 UTC


README

Laravel 5.x 框架的购物车实现

重要信息

这是 Darryl Fernandez 的出色软件包 Laravel Shopping Cart 的分支。
分支是为了使其兼容 Laravel 5.4 并向公众提供。
尽管如此,我们并不责怪 Darryl(我们每个人都有私生活,这是第一位的),但他的出色工作值得赞扬。
由于 Darryl 仍在处理他的购物车,你可以切换到他的版本,或者你可以留在这里看看这里发生了什么。

安装

使用 Composer 安装软件包。

composer require frezno/freznocart

配置

打开 config/app.php 文件。

将此行添加到你的 Service Providers 数组中

Laravel 5.0 (PHP 5.4)

'Frezno\Cart\CartServiceProvider',

Laravel 5.1 及更高版本 (PHP >=5.5.9)

Frezno\Cart\CartServiceProvider::class,



并在下面,将此行添加到你的 Class Aliases 数组中

Laravel 5.0 (PHP 5.4)

'Cart' => 'Frezno\Cart\Facades\CartFacade',

Laravel 5.1 及更高版本 (PHP >=5.5.9)

'Cart' => Frezno\Cart\Facades\CartFacade::class,



如何使用 FreznoCart

用法

添加购物车项目: Cart::add()

你可以通过以下几种方式向购物车添加项目

/**
 * add item to the cart, it can be an array or multi dimensional array
 *
 * @param string|array $id
 * @param string $name
 * @param float $price
 * @param int $quantity
 * @param array $attributes
 * @param CartCondition|array $conditions
 * @return $this
 * @throws InvalidItemException
 */

// Simplest form to add item on your cart
Cart::add(455, 'Sample Item', 100.99, 2, array());

// array format
Cart::add(array(
    'id' => 456,
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'attributes' => array()
));

// add multiple items at one time
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'attributes' => array()
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'attributes' => array(
        'size' => 'L',
        'color' => 'blue'
      )
  ),
));

// NOTE:
// Please keep in mind that when adding an item on cart, the "id" should be unique as it serves as
// row identifier as well. If you provide same ID, it will assume the operation will be an update to its quantity
// to avoid cart item duplicates

更新购物车中的项目: Cart::update()

更新购物车中的项目非常简单

/**
 * update a cart
 *
 * @param $id (the item ID)
 * @param array $data
 *
 * the $data will be an associative array, you don't need to pass all the data, only the key value
 * of the item you want to update on it
 */

Cart::update(456, array(
  'name' => 'New Item Name', // new item name
  'price' => 98.67, // new item price, price can also be a string format like so: '98.67'
));

// you may also want to update a product's quantity
Cart::update(456, array(
  'quantity' => 2, // so if the current product has a quantity of 4, another 2 will be added so this will result to 6
));

// you may also want to update a product by reducing its quantity, you do this like so:
Cart::update(456, array(
  'quantity' => -1, // so if the current product has a quantity of 4, it will subtract 1 and will result to 3
));

// NOTE: as you can see by default, the quantity update is relative to its current value
// if you want to just totally replace the quantity instead of incrementing or decrementing its current quantity value
// you can pass an array in quantity value like so:
Cart::update(456, array(
  'quantity' => array(
      'relative' => false,
      'value' => 5
  ),
));
// so with that code above as relative is flagged as false, if the item's quantity before is 2 it will now be 5 instead of
// 5 + 2 which results to 7 if updated relatively..

从购物车中删除项目: Cart::remove()

从购物车中删除项目非常容易

/**
 * removes an item on cart by item ID
 *
 * @param $id
 */

Cart::remove(456);

获取购物车中的项目: Cart::get()

/**
 * get an item on a cart by item ID
 * if item ID is not found, this will return null
 *
 * @param $itemId
 * @return null|array
 */

$itemId = 456;

Cart::get($itemId);

// You can also get the sum of the Item multiplied by its quantity, see below:
$summedPrice = Cart::get($itemId)->getPriceSum();

获取购物车内容和数量: Cart::getContent()

/**
 * get the cart
 *
 * @return CartCollection
 */

$cartCollection = Cart::getContent();

// NOTE: Because cart collection extends Laravel's Collection
// You can use methods you already know about Laravel's Collection
// See some of its method below:

// count carts contents
$cartCollection->count();

// transformations
$cartCollection->toArray();
$cartCollection->toJson();

检查购物车是否为空: Cart::isEmpty()

/**
* check if cart is empty
*
* @return bool
*/
Cart::isEmpty();

获取购物车总数量: Cart::getTotalQuantity()

/**
* get total quantity of items in the cart
*
* @return int
*/
$cartTotalQuantity = Cart::getTotalQuantity();

获取购物车小计: Cart::getSubTotal()

/**
* get cart sub total
*
* @return float
*/
$subTotal = Cart::getSubTotal();

获取购物车总额: Cart::getTotal()

/**
 * the new total in which conditions are already applied
 *
 * @return float
 */
$total = Cart::getTotal();

清空购物车: Cart::clear()

/**
* clear cart
*
* @return void
*/
Cart::clear();

条件

Laravel 购物车支持购物车条件。条件在例如优惠券、折扣、促销、按项目促销和折扣等方面非常有用。请仔细查看以下如何使用条件。

条件可以添加在

1.) 整个购物车价值基础

2.) 按项目基础

首先,让我们在购物车基础上添加一个条件

也有几种方法可以在购物车上添加条件。
注意

当在购物车基础上添加条件时,'target' 应该有 'subtotal' 的值。当在项目中添加条件时,'target' 应该是 'item'。计算顺序也会根据你添加条件的顺序而变化。

此外,在添加条件时,'value' 字段将是计算的基础。

// add single condition on a cart bases
$condition = new \Frezno\Cart\CartCondition(array(
    'name' => 'VAT 12.5%',
    'type' => 'tax',
    'target' => 'subtotal',
    'value' => '12.5%',
    'attributes' => array( // attributes field is optional
    	'description' => 'Value added tax',
    	'more_data' => 'more data here'
    )
));

Cart::condition($condition);

// or add multiple conditions from different condition instances
$condition1 = new \Frezno\Cart\CartCondition(array(
    'name' => 'VAT 12.5%',
    'type' => 'tax',
    'target' => 'subtotal',
    'value' => '12.5%',
    'order' => 2
));

$condition2 = new \Frezno\Cart\CartCondition(array(
    'name' => 'Express Shipping $15',
    'type' => 'shipping',
    'target' => 'subtotal',
    'value' => '+15',
    'order' => 1
));

Cart::condition($condition1);
Cart::condition($condition2);

// The property 'Order' lets you add different conditions through for example a shopping process with multiple
// pages and still be able to set an order to apply the conditions. If no order is defined defaults to 0

// or add multiple conditions as array
Cart::condition([$condition1, $condition2]);

// To get all applied conditions on a cart, use below:
$cartConditions = Cart::getConditions();
foreach($carConditions as $condition)
{
    $condition->getTarget(); // the target of which the condition was applied
    $condition->getName(); // the name of the condition
    $condition->getType(); // the type
    $condition->getValue(); // the value of the condition
    $condition->getOrder(); // the order of the condition
    $condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added
}

// You can also get a condition that has been applied on the cart by using its name, use below:
$condition = Cart::getCondition('VAT 12.5%');
$condition->getTarget(); // the target of which the condition was applied
$condition->getName(); // the name of the condition
$condition->getType(); // the type
$condition->getValue(); // the value of the condition
$condition->getAttributes(); // the attributes of the condition, returns an empty [] if no attributes added

// You can get the conditions calculated value by providing the subtotal, see below:
$subTotal = Cart::getSubTotal();
$condition = Cart::getCondition('VAT 12.5%');
$conditionCalculatedValue = $condition->getCalculatedValue($subTotal);

注意:所有基于购物车的条件都应该在调用 Cart::getTotal() 之前应用。

最后,您可以通过调用 Cart::getTotal() 来获取应用了条件后的购物车总价。

$cartTotal = Cart::getTotal(); // the total will be calculated based on the conditions you ave provided

接下来是按项目基础的条件。

如果您有优惠券需要具体应用在某个项目上而不是整个购物车价值上,这将非常有用。

注意:在按项目基础添加条件时,'target' 应该具有值为 'item'。

现在让我们添加一个项目条件。

// lets create first our condition instance
$saleCondition = new \Frezno\Cart\CartCondition(array(
            'name' => 'SALE 5%',
            'type' => 'tax',
            'target' => 'item',
            'value' => '-5%',
        ));

// now the product to be added on cart
$product = array(
            'id' => 456,
            'name' => 'Sample Item 1',
            'price' => 100,
            'quantity' => 1,
            'attributes' => array(),
            'conditions' => $saleCondition
        );

// finally add the product on the cart
Cart::add($product);

// you may also add multiple condition on an item
$itemCondition1 = new \Frezno\Cart\CartCondition(array(
    'name' => 'SALE 5%',
    'type' => 'sale',
    'target' => 'item',
    'value' => '-5%',
));

$itemCondition2 = new CartCondition(array(
    'name' => 'Item Gift Pack 25.00',
    'type' => 'promo',
    'target' => 'item',
    'value' => '-25',
));

$itemCondition3 = new \Frezno\Cart\CartCondition(array(
    'name' => 'MISC',
    'type' => 'misc',
    'target' => 'item',
    'value' => '+10',
));

$item = array(
          'id' => 456,
          'name' => 'Sample Item 1',
          'price' => 100,
          'quantity' => 1,
          'attributes' => array(),
          'conditions' => [$itemCondition1, $itemCondition2, $itemCondition3]
      );

Cart::add($item);

注意:在调用 Cart::getSubTotal() 之前,应该先应用所有购物车按项目条件。

然后最终您可以调用 Cart::getSubTotal() 来获取应用了条件后的购物车子总价。

$cartSubTotal = Cart::getSubTotal(); // the subtotal will be calculated based on the conditions you have provided

向购物车中的现有项目添加条件: Cart::addItemCondition($productId, $itemCondition)

向购物车中的现有项目添加条件同样简单。

这在结账过程中添加新的项目条件(如优惠券和促销代码)时非常有用。让我们看看如何实现示例。

$productID = 456;
$coupon101 = new CartCondition(array(
            'name' => 'COUPON 101',
            'type' => 'coupon',
            'target' => 'item',
            'value' => '-5%',
        ));

Cart::addItemCondition($productID, $coupon101);

清除购物车条件: Cart::clearCartConditions()

/**
* clears all conditions on a cart,
* this does not remove conditions that has been added specifically to an item/product.
* If you wish to remove a specific condition to a product, you may use the method: removeItemCondition($itemId,$conditionName)
*
* @return void
*/
Cart::clearCartConditions()

移除特定的购物车条件: Cart::removeCartCondition($conditionName)

/**
* removes a condition on a cart by condition name,
* this can only remove conditions that are added on cart bases not conditions that are added on an item/product.
* If you wish to remove a condition that has been added for a specific item/product, you may
* use the removeItemCondition(itemId, conditionName) method instead.
*
* @param $conditionName
* @return void
*/
$conditionName = 'Summer Sale 5%';

Cart::removeCartCondition($conditionName)

移除特定的项目条件: Cart::removeItemCondition($itemId, $conditionName)

/**
* remove a condition that has been applied on an item that is already on the cart
*
* @param $itemId
* @param $conditionName
* @return bool
*/
Cart::removeItemCondition($itemId, $conditionName)

清除所有项目条件: Cart::clearItemConditions($itemId)

/**
* remove all conditions that has been applied on an item that is already on the cart
*
* @param $itemId
* @return bool
*/
Cart::clearItemConditions($itemId)

按类型获取条件: Cart::getConditionsByType($type)

/**
* Get all the condition filtered by Type
* Please Note that this will only return condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return CartConditionCollection
*/
public function getConditionsByType($type)

按类型移除条件: Cart::removeConditionsByType($type)

/**
* Remove all the condition with the $type specified
* Please Note that this will only remove condition added on cart bases, not those conditions added
* specifically on an per item bases
*
* @param $type
* @return $this
*/
public function removeConditionsByType($type)

项目

Cart::getContent() 方法返回一个包含项目的集合。

要获取项目的 ID,使用属性 $item->id

要获取项目的名称,使用属性 $item->name

要获取项目的数量,使用属性 $item->quantity

要获取项目的属性,使用属性 $item->attributes

要获取未应用条件的一个项目的价格,使用属性 $item->price

要获取未应用条件的一个项目的总价,使用方法 $item->getPriceSum()

/**
* get the sum of price
*
* @return mixed|null
*/
public function getPriceSum()

要获取未应用条件的一个项目的价格,使用方法

$item->getPriceWithConditions().

/**
* get the single price in which conditions are already applied
*
* @return mixed|null
*/
public function getPriceWithConditions()

要获取应用了条件的一个项目的总价,使用方法

$item->getPriceSumWithConditions()

/**
* get the sum of price in which conditions are already applied
*
* @return mixed|null
*/
public function getPriceSumWithConditions()

注意:当获取应用了条件的价格时,仅计算分配给当前项目的条件。购物车条件不会应用于价格。

实例

您可能希望在同一个页面上创建多个购物车实例,而不会产生冲突。为此,

创建一个新的 Service Provider,然后在 register() 方法中,您可以这样设置

$this->app['wishlist'] = $this->app->share(function($app)
{
	$storage = $app['session']; // laravel session storage
		$events = $app['events']; // laravel event handler
		$instanceName = 'wishlist'; // your cart instance name
		$session_key = 'AsASDMCks0ks1'; // your unique session key to hold cart items

	return new Cart(
		$storage,
		$events,
		$instanceName,
		$session_key
	);
});

异常

目前只有两种异常。

异常 描述
InvalidConditionException 在实例化新的 Condition 时存在无效的字段值
InvalidItemException 当新产品有无效的字段值(id、name、price、quantity)时

事件

购物车目前有 9 个事件您可以监听并挂钩一些动作。

事件 触发
cart.created($cart) 当购物车被实例化时
cart.adding($items, $cart) 当尝试添加一个项目时
cart.added($items, $cart) 当一个项目被添加到购物车时
cart.updating($items, $cart) 当项目正在被更新时
cart.updated($items, $cart) 当一个项目被更新时
cart.removing($id, $cart) 当项目正在被移除时
cart.removed($id, $cart) 当一个项目被移除时
cart.clearing($cart) 当尝试清除购物车时
cart.cleared($cart) 当购物车被清除时

注意:对于不同的购物车实例,处理事件很简单。例如,您已创建另一个购物车实例,并将其实例名称命名为“心愿单”。事件将类似于:{$instanceName}.created($cart)

因此,对于您的心愿单购物车实例,事件将如下所示

  • wishlist.created($cart)
  • wishlist.adding($items, $cart)
  • wishlist.added($items, $cart) 等等。

响应格式化

现在您可以格式化所有响应。您可以从包中发布配置文件或使用环境变量来设置配置。您拥有的选项有

  • format_numbers 或 env('SHOPPING_FORMAT_VALUES', false) => 激活或禁用此功能。默认为 false,
  • decimals 或 env('SHOPPING_DECIMALS', 0) => 您想显示的小数位数。默认为 0。
  • dec_point 或 env('SHOPPING_DEC_POINT', '.') => 小数点类型。默认为 '.'。
  • thousands_sep 或 env('SHOPPING_THOUSANDS_SEP', ',') => 值的千位分隔符。默认为 ','。

示例

// add items to cart
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'attributes' => array()
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'attributes' => array(
        'size' => 'L',
        'color' => 'blue'
      )
  ),
));

// then you can:
$items = Cart::getContent();

foreach($items as $item)
{
    $item->id; // the Id of the item
    $item->name; // the name
    $item->price; // the single price without conditions applied
    $item->getPriceSum(); // the subtotal without conditions applied
    $item->getPriceWithConditions(); // the single price with conditions applied
    $item->getPriceSumWithConditions(); // the subtotal with conditions applied
    $item->quantity; // the quantity
    $item->attributes; // the attributes

    // Note that attribute returns ItemAttributeCollection object that extends the native laravel collection
    // so you can do things like below:

    if( $item->attributes->has('size') )
    {
        // item has attribute size
    }
    else
    {
        // item has no attribute size
    }
}

// or
$items->each(function($item)
{
    $item->id; // the Id of the item
    $item->name; // the name
    $item->price; // the single price without conditions applied
    $item->getPriceSum(); // the subtotal without conditions applied
    $item->getPriceWithConditions(); // the single price with conditions applied
    $item->getPriceSumWithConditions(); // the subtotal with conditions applied
    $item->quantity; // the quantity
    $item->attributes; // the attributes

    if( $item->attributes->has('size') )
    {
        // item has attr

        ibute size
    }
    else
    {
        // item has no attribute size
    }
});

变更日志

开始于 Darryls 版本 **2.4.0 当分叉时。

许可

Laravel 购物车是开源软件,遵循 MIT 许可

免责声明

本软件按“原样”提供,并排除了任何明示或暗示的保证,包括但不限于对适销性和针对特定目的的适用性的暗示保证。在任何情况下,作者或任何贡献者都不对任何直接、间接、偶然、特殊、示范性或后果性的损害(包括但不限于替代货物或服务的采购;使用、数据或利润的损失;或业务中断)负责,无论这些损害是由于何种原因和何种责任理论(包括疏忽或其他)引起的,即使被告知本软件可能造成此类损害。