scott-lsi / laravelshoppingbasket
Laravel 购物篮
Requires
- php: >=8.1
- illuminate/support: ^10.0
- illuminate/translation: ^10.0
- illuminate/validation: ^10.0
Requires (Dev)
- mockery/mockery: ^1.4.2
- orchestra/testbench: ^4.0|^5.0|^6.0|^7.0|^8.0
- phpunit/phpunit: ^10.0
This package is auto-updated.
Last update: 2024-09-28 18:58:50 UTC
README
致谢
这是基于 ultrono/laravelshoppingcart-1 的分支,而该分支是 darryldecode/laravelshoppingbasket 的分支。
安装
composer require scott-lsi/laravelshoppingbasket
配置
服务提供者和别名是自动发现的。
您可以使用以下命令发布配置文件:
php artisan vendor:publish --provider="ScottLsi\Basket\BasketServiceProvider" --tag="config"
如何使用
快速使用示例
// Quick Usage with the Product Model Association & User session binding $Product = Product::find($productId); // assuming you have a Product model with id, name, description & price $rowId = 456; // generate a unique() row ID $userID = 2; // the user ID to bind the basket contents // add the product to basket \Basket::session($userID)->add(array( 'id' => $rowId, 'name' => $Product->name, 'price' => $Product->price, 'quantity' => 4, 'attributes' => array(), 'associatedModel' => $Product )); // update the item on basket \Basket::session($userID)->update($rowId,[ 'quantity' => 2, 'price' => 98.67 ]); // delete an item on basket \Basket::session($userID)->remove($rowId); // view the basket items $items = \Basket::getContent(); foreach($items as $row) { echo $row->id; // row ID echo $row->name; echo $row->qty; echo $row->price; echo $item->associatedModel->id; // whatever properties your model have echo $item->associatedModel->name; // whatever properties your model have echo $item->associatedModel->description; // whatever properties your model have } // FOR FULL USAGE, SEE BELOW..
用法
重要提示!
默认情况下,购物篮有一个默认的sessionKey来存储购物篮数据。这也作为购物篮的唯一标识符,您可以使用它将购物篮绑定到特定用户。要覆盖此默认会话键,您只需在调用任何其他方法之前简单地调用 \Basket::session($sessionKey)
方法即可。
示例
$userId // the current login user id // This tells the basket that we only need or manipulate // the basket data of a specific user. It doesn't need to be $userId, // you can use any unique key that represents a unique to a user or customer. // basically this binds the basket to a specific user. \Basket::session($userId); // then followed by the normal basket usage \Basket::add(); \Basket::update(); \Basket::remove(); \Basket::condition($condition1); \Basket::getTotal(); \Basket::getSubTotal(); \Basket::addItemCondition($productID, $coupon101); // and so on..
下面有更多示例
向购物篮添加项目: Basket::add()
您有几种方法可以向购物篮添加项目,请参见以下内容
/** * add item to the basket, 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 BasketCondition|array $conditions * @return $this * @throws InvalidItemException */ # ALWAYS REMEMBER TO BIND THE CART TO A USER BEFORE CALLING ANY CART FUNCTION # SO CART WILL KNOW WHO'S CART DATA YOU WANT TO MANIPULATE. SEE IMPORTANT NOTICE ABOVE. # EXAMPLE: \Basket::session($userId); then followed by basket normal usage. # NOTE: # the 'id' field in adding a new item on basket is not intended for the Model ID (example Product ID) # instead make sure to put a unique ID for every unique product or product that has it's own unique prirce, # because it is used for updating basket and how each item on basket are segregated during calculation and quantities. # You can put the model_id instead as an attribute for full flexibility. # Example is that if you want to add same products on the basket but with totally different attribute and price. # If you use the Product's ID as the 'id' field in basket, it will result to increase in quanity instead # of adding it as a unique product with unique attribute and price. // Simplest form to add item on your basket Basket::add(455, 'Sample Item', 100.99, 2, array()); // array format Basket::add(array( 'id' => 456, // inique row ID 'name' => 'Sample Item', 'price' => 67.99, 'quantity' => 4, 'attributes' => array() )); // add multiple items at one time Basket::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' ) ), )); // add basket items to a specific user $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->add(array( 'id' => 456, // inique row ID 'name' => 'Sample Item', 'price' => 67.99, 'quantity' => 4, 'attributes' => array(), 'associatedModel' => $Product )); // NOTE: // Please keep in mind that when adding an item on basket, 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 basket item duplicates
更新购物篮上的项目: Basket::update()
更新购物篮上的项目非常简单
/** * update a basket * * @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 */ Basket::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 Basket::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: Basket::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: Basket::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.. // updating a basket for a specific user $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->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' ));
从购物篮中删除项目: Basket::remove()
从购物篮中删除项目非常简单
/** * removes an item on basket by item ID * * @param $id */ Basket::remove(456); // removing basket item for a specific user's basket $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->remove(456);
获取购物篮上的项目: Basket::get()
/** * get an item on a basket by item ID * if item ID is not found, this will return null * * @param $itemId * @return null|array */ $itemId = 456; Basket::get($itemId); // You can also get the sum of the Item multiplied by its quantity, see below: $summedPrice = Basket::get($itemId)->getPriceSum(); // get an item on a basket by item ID for a specific user's basket $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->get($itemId);
获取购物篮的内容和计数: Basket::getContent()
/** * get the basket * * @return BasketCollection */ $basketCollection = Basket::getContent(); // NOTE: Because basket collection extends Laravel's Collection // You can use methods you already know about Laravel's Collection // See some of its method below: // count baskets contents $basketCollection->count(); // transformations $basketCollection->toArray(); $basketCollection->toJson(); // Getting basket's contents for a specific user $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->getContent($itemId);
检查购物篮是否为空: Basket::isEmpty()
/** * check if basket is empty * * @return bool */ Basket::isEmpty(); // Check if basket's contents is empty for a specific user $userId = auth()->user()->id; // or any string represents user identifier Basket::session($userId)->isEmpty();
获取购物篮的总数量: Basket::getTotalQuantity()
/** * get total quantity of items in the basket * * @return int */ $basketTotalQuantity = Basket::getTotalQuantity(); // for a specific user $basketTotalQuantity = Basket::session($userId)->getTotalQuantity();
获取购物篮的小计: Basket::getSubTotal()
/** * get basket sub total * * @return float */ $subTotal = Basket::getSubTotal(); // for a specific user $subTotal = Basket::session($userId)->getSubTotal();
获取购物篮的总计: Basket::getTotal()
/** * the new total in which conditions are already applied * * @return float */ $total = Basket::getTotal(); // for a specific user $total = Basket::session($userId)->getTotal();
清除购物篮: Basket::clear()
/** * clear basket * * @return void */ Basket::clear(); Basket::session($userId)->clear();
条件
Laravel 购物篮支持购物篮条件。条件在(优惠券、折扣、促销、按项目促销和折扣等)方面非常有用。请仔细阅读以下内容,了解如何使用条件。
条件可以添加在
1.) 整个购物篮价值的基础上
2.) 每个项目的基础上
首先,让我们在购物篮基础上添加一个条件
也有几种方法可以在购物篮上添加条件:注意
当在购物篮基础上添加条件时,'target' 的值应该是 'subtotal' 或 'total'。如果目标是 "subtotal",则此条件将应用于小计。如果目标是 "total",则此条件将应用于总计。在计算时的操作顺序也会根据您添加条件的顺序而变化。
此外,在添加条件时,'value' 字段将是计算的基础。您可以通过在 BasketCondition 中添加 'order' 参数来改变此顺序。
// add single condition on a basket bases $condition = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'VAT 12.5%', 'type' => 'tax', 'target' => 'subtotal', // this condition will be applied to basket's subtotal when getSubTotal() is called. 'value' => '12.5%', 'attributes' => array( // attributes field is optional 'description' => 'Value added tax', 'more_data' => 'more data here' ) )); Basket::condition($condition); Basket::session($userId)->condition($condition); // for a speicifc user's basket // or add multiple conditions from different condition instances $condition1 = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'VAT 12.5%', 'type' => 'tax', 'target' => 'subtotal', // this condition will be applied to basket's subtotal when getSubTotal() is called. 'value' => '12.5%', 'order' => 2 )); $condition2 = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'Express Shipping $15', 'type' => 'shipping', 'target' => 'subtotal', // this condition will be applied to basket's subtotal when getSubTotal() is called. 'value' => '+15', 'order' => 1 )); Basket::condition($condition1); Basket::condition($condition2); // Note that after adding conditions that are targeted to be applied on subtotal, the result on getTotal() // will also be affected as getTotal() depends in getSubTotal() which is the subtotal. // add condition to only apply on totals, not in subtotal $condition = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'Express Shipping $15', 'type' => 'shipping', 'target' => 'total', // this condition will be applied to basket's total when getTotal() is called. 'value' => '+15', 'order' => 1 // the order of calculation of basket base conditions. The bigger the later to be applied. )); Basket::condition($condition); // The property 'order' lets you control the sequence of conditions when calculated. Also it 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 // NOTE!! On current version, 'order' parameter is only applicable for conditions for basket bases. It does not support on per item conditions. // or add multiple conditions as array Basket::condition([$condition1, $condition2]); // To get all applied conditions on a basket, use below: $basketConditions = Basket::getConditions(); foreach($basketConditions 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 basket by using its name, use below: $condition = Basket::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 = Basket::getSubTotal(); $condition = Basket::getCondition('VAT 12.5%'); $conditionCalculatedValue = $condition->getCalculatedValue($subTotal);
注意:所有基于购物篮的条件都应该在调用 Basket::getTotal() 之前添加到购物篮的条件中,如果还有针对小计的目标条件,则应在调用 Basket::getSubTotal() 之前添加到购物篮的条件中。
$basketTotal = Basket::getSubTotal(); // the subtotal with the conditions targeted to "subtotal" applied $basketTotal = Basket::getTotal(); // the total with the conditions targeted to "total" applied $basketTotal = Basket::session($userId)->getSubTotal(); // for a specific user's basket $basketTotal = Basket::session($userId)->getTotal(); // for a specific user's basket
接下来是每个项目基础上的条件。
如果您有特定的优惠券要应用于单个项目而不是整个购物篮价值,这非常有用。
注意:在按项目基础上添加条件时,'target' 参数不是必需的或可以省略,与添加条件或购物篮基础不同。
现在让我们添加一个项目条件。
// lets create first our condition instance $saleCondition = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'SALE 5%', 'type' => 'tax', 'value' => '-5%', )); // now the product to be added on basket $product = array( 'id' => 456, 'name' => 'Sample Item 1', 'price' => 100, 'quantity' => 1, 'attributes' => array(), 'conditions' => $saleCondition ); // finally add the product on the basket Basket::add($product); // you may also add multiple condition on an item $itemCondition1 = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'SALE 5%', 'type' => 'sale', 'value' => '-5%', )); $itemCondition2 = new BasketCondition(array( 'name' => 'Item Gift Pack 25.00', 'type' => 'promo', 'value' => '-25', )); $itemCondition3 = new \ScottLsi\Basket\BasketCondition(array( 'name' => 'MISC', 'type' => 'misc', 'value' => '+10', )); $item = array( 'id' => 456, 'name' => 'Sample Item 1', 'price' => 100, 'quantity' => 1, 'attributes' => array(), 'conditions' => [$itemCondition1, $itemCondition2, $itemCondition3] ); Basket::add($item);
注意:所有基于购物篮的每个项目条件都应该在调用 Basket::getSubTotal() 之前添加。
最后,您可以调用 Basket::getSubTotal() 来获取应用了每个商品条件的购物车小计。
// the subtotal will be calculated based on the conditions added that has target => "subtotal" // and also conditions that are added on per item $basketSubTotal = Basket::getSubTotal();
向购物车中现有的商品添加条件: Basket::addItemCondition($productId, $itemCondition)
向购物车中现有的商品添加条件同样简单。
当在结账过程中添加商品的新条件,如优惠券和促销代码时,这非常有用。让我们看看如何操作的例子。
$productID = 456; $coupon101 = new BasketCondition(array( 'name' => 'COUPON 101', 'type' => 'coupon', 'value' => '-5%', )); Basket::addItemCondition($productID, $coupon101);
清除购物车条件: Basket::clearBasketConditions()
/** * clears all conditions on a basket, * 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 */ Basket::clearBasketConditions()
移除特定的购物车条件: Basket::removeBasketCondition($conditionName)
/** * removes a condition on a basket by condition name, * this can only remove conditions that are added on basket 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%'; Basket::removeBasketCondition($conditionName)
移除特定的商品条件: Basket::removeItemCondition($itemId, $conditionName)
/** * remove a condition that has been applied on an item that is already on the basket * * @param $itemId * @param $conditionName * @return bool */ Basket::removeItemCondition($itemId, $conditionName)
清除所有商品条件: Basket::clearItemConditions($itemId)
/** * remove all conditions that has been applied on an item that is already on the basket * * @param $itemId * @return bool */ Basket::clearItemConditions($itemId)
按类型获取条件: Basket::getConditionsByType($type)
/** * Get all the condition filtered by Type * Please Note that this will only return condition added on basket bases, not those conditions added * specifically on an per item bases * * @param $type * @return BasketConditionCollection */ public function getConditionsByType($type)
按类型移除条件: Basket::removeConditionsByType($type)
/** * Remove all the condition with the $type specified * Please Note that this will only remove condition added on basket bases, not those conditions added * specifically on an per item bases * * @param $type * @return $this */ public function removeConditionsByType($type)
项目
Basket::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()
注意:当您获取应用了条件的价格时,仅计算分配给当前商品的条件。购物车条件不会应用于价格。
关联模型
可以将购物车商品关联到一个模型。假设您在应用程序中有一个 Product
模型。使用 associate()
方法,您可以告诉购物车,购物车中的一个项目与 Product
模型相关联。
这样,您就可以通过属性 $item->model 访问您的模型。
以下是一个例子
// add the item to the basket. $basketItem = Basket::add(455, 'Sample Item', 100.99, 2, array())->associate('Product'); // array format Basket::add(array( 'id' => 456, 'name' => 'Sample Item', 'price' => 67.99, 'quantity' => 4, 'attributes' => array(), 'associatedModel' => 'Product' )); // add multiple items at one time Basket::add(array( array( 'id' => 456, 'name' => 'Sample Item 1', 'price' => 67.99, 'quantity' => 4, 'attributes' => array(), 'associatedModel' => 'Product' ), array( 'id' => 568, 'name' => 'Sample Item 2', 'price' => 69.25, 'quantity' => 4, 'attributes' => array( 'size' => 'L', 'color' => 'blue' ), 'associatedModel' => 'Product' ), )); // Now, when iterating over the content of the basket, you can access the model. foreach(Basket::getContent() as $row) { echo 'You have ' . $row->qty . ' items of ' . $row->model->name . ' with description: "' . $row->model->description . '" in your basket.'; }
注意:这仅在向购物车添加项目时有效。
实例
您可能还希望在同一个页面上使用多个购物车实例而不会发生冲突。为此,
创建一个新的 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 basket instance name $session_key = 'AsASDMCks0ks1'; // your unique session key to hold basket items return new Basket( $storage, $events, $instanceName, $session_key ); }); // for 5.4 or newer use ScottLsi\Basket\Basket; use Illuminate\Support\ServiceProvider; class WishListProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('wishlist', function($app) { $storage = $app['session']; $events = $app['events']; $instanceName = 'basket_2'; $session_key = '88uuiioo99888'; return new Basket( $storage, $events, $instanceName, $session_key, config('shopping_basket') ); }); } }
如果您在多个购物车实例上遇到问题,请参阅此演示代码库中的代码:[DEMO](https://github.com/darryldecode/laravelshoppingbasket-demo)
异常
目前只有两个异常。
事件
购物车目前有 9 个事件可供监听和挂钩操作。
注意:对于不同的购物车实例,处理事件很简单。例如,您创建了另一个购物车实例,给它命名为 "wishlist"。事件将类似于:{$instanceName}.created($basket)
因此,对于您的 wishlist 购物车实例,事件将如下所示
- wishlist.created($basket)
- wishlist.adding($items, $basket)
- wishlist.added($items, $basket) 等等。
响应格式
现在,您可以格式化所有响应。您可以从包中发布配置文件或使用 env 变量来设置配置。您有的选项是
- 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 basket Basket::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 = Basket::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 attribute size } else { // item has no attribute size } });
存储
为篮子商品使用不同的存储方式非常简单。注入到篮子实例的存储类只需要提供方法。
例如,我们需要一个愿望单,我们希望将其键值对存储在数据库中,而不是默认的会话。
为此,我们首先需要一个数据库表来存储我们的篮子数据。让我们通过执行php artisan make:migration create_basket_storage_table
来创建它。
示例代码
use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBasketStorageTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('basket_storage', function (Blueprint $table) { $table->string('id')->index(); $table->longText('basket_data'); $table->timestamps(); $table->primary('id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('basket_storage'); } }
接下来,让我们在这个表上创建一个eloquent模型,这样我们就可以轻松地处理数据。你可以选择将这个模型存储在哪里。对于这个例子,我们假设将其存储在我们的App命名空间中。
代码
namespace App; use Illuminate\Database\Eloquent\Model; class DatabaseStorageModel extends Model { protected $table = 'basket_storage'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'id', 'basket_data', ]; public function setBasketDataAttribute($value) { $this->attributes['basket_data'] = serialize($value); } public function getBasketDataAttribute($value) { return unserialize($value); } }
接下来,为要注入到我们的篮子实例中的存储创建一个新的类
例如。
class DBStorage { public function has($key) { return DatabaseStorageModel::find($key); } public function get($key) { if($this->has($key)) { return new BasketCollection(DatabaseStorageModel::find($key)->basket_data); } else { return []; } } public function put($key, $value) { if($row = DatabaseStorageModel::find($key)) { // update $row->basket_data = $value; $row->save(); } else { DatabaseStorageModel::create([ 'id' => $key, 'basket_data' => $value ]); } } }
例如,你也可以使用下面的示例利用Laravel的缓存(redis、memcached、文件、dynamo等)。示例还包括cookie持久性,这样篮子就可以在30天内仍然可用。默认情况下,会话只持续20分钟。
namespace App\Basket; use Carbon\Carbon; use Cookie; use ScottLsi\Basket\BasketCollection; class CacheStorage { private $data = []; private $basket_id; public function __construct() { $this->basket_id = \Cookie::get('basket'); if ($this->basket_id) { $this->data = \Cache::get('basket_' . $this->basket_id, []); } else { $this->basket_id = uniqid(); } } public function has($key) { return isset($this->data[$key]); } public function get($key) { return new BasketCollection($this->data[$key] ?? []); } public function put($key, $value) { $this->data[$key] = $value; \Cache::put('basket_' . $this->basket_id, $this->data, Carbon::now()->addDays(30)); if (!Cookie::hasQueued('basket')) { Cookie::queue( Cookie::make('basket', $this->basket_id, 60 * 24 * 30) ); } } }
为了使其成为篮子的默认存储,让我们更新篮子的配置文件。首先,让我们发布篮子配置文件,以便我们能够覆盖它。php artisan vendor:publish --provider="ScottLsi\Basket\BasketServiceProvider" --tag="config"
运行该命令后,在你的配置文件夹中应该有一个名为shopping_basket.php
的新文件。
打开这个文件,让我们更新存储使用。找到键为'storage' => null,
将其更新为你的新创建的DBStorage类,在我们的例子中,'storage' => \App\DBStorage::class,
或者,如果你有多个篮子实例(例如愿望单),你可以通过将自定义数据库存储注入到愿望单篮子的服务提供者中来注入自定义数据库存储,替换存储为你的自定义存储。请看下面的示例
use ScottLsi\Basket\Basket; use Illuminate\Support\ServiceProvider; class WishListProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('wishlist', function($app) { $storage = new DBStorage(); <-- Your new custom storage $events = $app['events']; $instanceName = 'basket_2'; $session_key = '88uuiioo99888'; return new Basket( $storage, $events, $instanceName, $session_key, config('shopping_basket') ); }); } }
许可证
Laravel购物篮是开源软件,许可证为MIT许可证
免责声明
本软件按“原样”提供,并明确或暗示地放弃了任何保证,包括但不限于适销性和特定目的的适用性暗示保证。在任何情况下,作者或任何贡献者均不对任何直接、间接、偶然、特殊、示范性或后果性损害(包括但不限于替代货物或服务的采购;使用、数据或利润的损失;或业务中断)承担责任,无论何种原因和任何责任理论(合同、严格责任或侵权(包括疏忽或不作为)),即使已告知此类损害的可能性。