ozanmuyes / laravel5cart
Laravel 5 购物车
Requires
- php: >=5.4.0
- illuminate/support: 5.0.x|5.1.x
- illuminate/validation: 5.0.x|5.1.x
Requires (Dev)
- mockery/mockery: ~0.9
- phpunit/phpunit: ~4.0
- symfony/var-dumper: 2.7.*@dev
README
基于 Laravel 框架的购物车实现(基于 darryldecode 的出色工作 darryldecode)
##安装
通过 Composer 安装此软件包。通过在项目的 composer.json
文件中添加以下内容来编辑:
"require": { "ozanmuyes/cart": "dev-master" }
接下来,从终端运行 Composer 更新命令
composer update
或者
composer update "ozanmuyes/cart"
##配置
- 打开 config/app.php 并将此行添加到服务提供者数组中
Ozanmuyes\Cart\CartServiceProvider::class
- 打开 config/app.php 并将此行添加到别名中
"Cart" => Ozanmuyes\Cart\Facades\CartFacade::class
##目录
##用法
在购物车中添加项目: 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.) 每个项目基础
首先,让我们在购物车基础上添加一个条件
向购物车中添加条件也有几种方法:注意
当在购物车基础上添加条件时,'目标'应具有值为'subtotal'。当在项目上添加条件时,'目标'应为'item'。在计算过程中,操作顺序也会因添加条件的顺序而异。
此外,在添加条件时,'值'字段将是计算的基础。
// add single condition on a cart bases $condition = new \Ozanmuyes\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 \Ozanmuyes\Cart\CartCondition(array( 'name' => 'VAT 12.5%', 'type' => 'tax', 'target' => 'subtotal', 'value' => '12.5%', )); $condition2 = new \Ozanmuyes\Cart\CartCondition(array( 'name' => 'Express Shipping $15', 'type' => 'shipping', 'target' => 'subtotal', 'value' => '+15', )); Cart::condition($condition1); Cart::condition($condition2); // 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->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
接下来是按项目基础的条件。
如果您有优惠券专门应用于项目而不是整个购物车价值,这将非常有用。
注意:当在按项目基础上添加条件时,'目标'应具有值为'item'。
现在让我们向项目添加条件。
// lets create first our condition instance $saleCondition = new \Ozanmuyes\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 \Ozanmuyes\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 \Ozanmuyes\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::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)
实例
您可能希望在同一个页面上使用多个购物车实例而不会发生冲突。为此,
创建一个新的服务提供商,然后在 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 | 在实例化新条件时存在无效的字段值 |
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) | 当购物车被清除时 |
注意:如果您已更改应用程序的命名空间,请在已发布的监听器上更正默认命名空间。
示例
// 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 price $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 price $item->quantity; // the quantity $item->attributes; // the attributes if( $item->attributes->has('size') ) { // item has attribute size } else { // item has no attribute size } });
变更日志
**2.4.0
- 在条件上添加了新方法:$condition->getAttributes();(请参阅条件部分)
**2.3.0
- 添加了新的购物车方法:Cart::addItemCondition($productId, $itemCondition)
- 添加了新的购物车方法:Cart::getTotalQuantity()
**2.2.1
- 修复了错误
**2.2.0
- 添加了新的购物车方法:Cart::getConditionsByType($type)
- 添加了新的项目方法:Cart::removeConditionsByType($type)
**2.1.1
- 当添加具有相同 ID 的新产品到购物车并提供数量时,它将增加其当前数量而不是覆盖它。您也可能需要更新项目数量,但不是增加而是减少,请参阅文档(请参阅 Cart::update() 部分,并仔细阅读)
**2.1.0
- 添加了新的购物车方法:getCalculatedValue($totalOrSubTotalOrPrice)
- 添加了新的项目方法:getPriceSum()
**2.0.0(重大更改**)
- 在处理条件方面有重大变化(请参阅条件部分,并仔细阅读)
- 现在,所有基于单个项目的条件都应具有 target => 'item' 而不是 'subtotal'。
- 现在,所有基于整个购物车的条件都应具有 target => 'subtotal' 而不是 'total'。
**1.1.0
- 添加了新方法:clearCartConditions()
- 添加了新方法:removeItemCondition($itemId, $conditionName)
- 添加了新方法:removeCartCondition($conditionName)
许可
该 Laravel 购物车软件是开源软件,遵循 MIT 许可协议
免责声明
本软件按“原样”提供,并明确或暗示地放弃了任何保证,包括但不限于对适销性和特定用途适用性的暗示保证。在任何情况下,作者或任何贡献者均不对因使用本软件而引起的任何直接、间接、偶然、特殊、示范性或后果性损害(包括但不限于替代商品或服务的采购;使用、数据或利润的损失;或业务中断)承担责任,无论此类损害是基于何种责任理论(合同、严格责任或侵权,包括疏忽或不作为)以及是否已告知此类损害的可能性。