ephra/shopping-cart

v1.0.1 2023-08-01 11:50 UTC

This package is auto-updated.

Last update: 2024-09-30 02:00:05 UTC


README

Total Downloads

购物车是一个实现,允许您在PHP应用程序中添加购物车部分

此包是一个适配版本,它基于并使用了Darrydecode Laravel Shopping Cart 包的多个函数: https://github.com/darryldecode/laravelshoppingcart

安装

通过 Composer 安装此包。

composer require ephra/shopping-cart

配置

  1. 创建文件 PhpSession.php,实现 SessionInterface。
Ephramago\Cart\Contracts\Session\SessionInterface::class
  1. 创建文件 CartConfig.php,返回配置数组参数
  return [
    'format_numbers' => false,
    'decimals' => 2,
    'dec_point' => '.',
    'thousands_sep' => ',',
]

如何使用

快速使用示例

// 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 cart contents
$phpSession = new PhpSession() // create new instance PhpSession
$cartConfig = require('CartConfig.php') // receive the config array in the file

// create new instance of cart
$cart = new Cart($phpSession, "shopping", $userID, $cartConfig)

// add the product to cart
$cart->session($userID)->add(array(
    'id' => $rowId,
    'name' => $Product->name,
    'price' => $Product->price,
    'quantity' => 4,
    'associatedModel' => $Product
));

// update the item on cart
$cart->session($userID)->update($rowId,[
	'quantity' => 2,
	'price' => 98.67
]);

// delete an item on cart
$cart->session($userID)->remove($rowId);

// view the cart items
$items = $cart->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,它保存购物车数据。这也作为购物车的唯一标识符,您可以将其用于将购物车绑定到特定用户。要覆盖此默认session Key,您只需在调用任何其他方法之前简单调用 $cart->session($sessionKey) 方法即可!!。

示例

$userId // the current login user id

// This tells the cart that we only need or manipulate
// the cart 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 cart to a specific user.
$cart->session($userId);

// then followed by the normal cart usage
$cart->add();
$cart->update();
$cart->remove();
$cart->getTotal();
// and so on..

下面有更多示例

在购物车中添加项目: 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 mixed $associatedModel
 * @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: $cart->session($userId); then followed by cart normal usage.

 # NOTE:
 # the 'id' field in adding a new item on cart 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 cart and how each item on cart 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 cart but with totally different attribute and price.
 # If you use the Product's ID as the 'id' field in cart, 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 cart
Cart::add(455, 'Sample Item', 100.99, 2, array());

// array format
Cart::add(array(
    'id' => 456, // inique row ID
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'associatedModel' => $Product
));

// add multiple items at one time
Cart::add(array(
  array(
      'id' => 456,
      'name' => 'Sample Item 1',
      'price' => 67.99,
      'quantity' => 4,
      'associatedModel' => $Product
  ),
  array(
      'id' => 568,
      'name' => 'Sample Item 2',
      'price' => 69.25,
      'quantity' => 4,
      'associatedModel' => $Product
  ),
));

// add cart items to a specific user
$userId = auth()->user()->id; // or any string represents user identifier
Cart::session($userId)->add(array(
    'id' => 456, // inique row ID
    'name' => 'Sample Item',
    'price' => 67.99,
    'quantity' => 4,
    'associatedModel' => $Product
));

// 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' => 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 cart for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
$cart->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'
));

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

从购物车中删除项目非常简单

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

$cart->remove(456);

// removing cart item for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
$cart->session($userId)->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)->getPrice();

// get an item on a cart by item ID for a specific user's cart
$userId = auth()->user()->id; // or any string represents user identifier
$cart->session($userId)->get($itemId);

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

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

$cartCollection = $cart->getContent();

// NOTE: Because cart collection
// See some of its method below:

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

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

// Getting cart's contents for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
$cart->session($userId)->getContent($itemId);

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

/**
* check if cart is empty
*
* @return bool
*/
$cart->isEmpty();

// Check if cart's contents is empty for a specific user
$userId = auth()->user()->id; // or any string represents user identifier
$cart->session($userId)->isEmpty();

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

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

// for a specific user
$cartTotalQuantity = $cart->session($userId)->getTotalQuantity();

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

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

// for a specific user
$total = $cart->session($userId)->getTotal();

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

/**
* clear cart
*
* @return void
*/
$cart->clear();
$cart->session($userId)->clear();

实例

您可能希望在同一页面上使用多个购物车实例而不发生冲突。为此,

创建一个新的 PhpSession 类,您可以将其放置如下

use Ephramago\Cart\Contracts\Session\SessionInterface;

class PhpSession implements SessionInterface
{
  /**
   * Checks if a key is present and not null.
   *
   * @param  string|int $key
   * @return bool
   */
  public function has($key)
  {
      $this->ensureStarted();
      return array_key_exists($key, $_SESSION);
  }

  /**
   * Get an item from the session.
   *
   * @param  string|int $key
   * @return mixed
   */
  public function get($key, $default = null)
  {
      $this->ensureStarted();
      return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
  }

  /**
   * Put a key / value pair or array of key / value pairs in the session.
   *
   * @param  string|array  $key
   * @param  mixed  $value
   * @return void
   */
  public function put($key, $value)
  {
      $this->ensureStarted();
      $_SESSION[$key] = $value;
  }

  /**
   * Remove an item from the session, returning its value.
   *
   * @param  string  $key
   * @return void
   */
  public function delete($key)
  {
      $this->ensureStarted();
      unset($_SESSION[$key]);
  }

  private function ensureStarted()
  {
      if (session_status() === PHP_SESSION_NONE) {
          session_start();
      }
  }
}

创建一个新的购物车文件配置

/* configCart.php */

return [
  'format_numbers' => false,
  'decimals' => 2,
  'dec_point' => '.',
  'thousands_sep' => ',',
];

创建一个新的 Cart 实例

$session = new PhpSession(); // PhpSession storage
$instanceName = 'my_cart'; // your cart instance name
$session_key = 'AsASDMCks0ks1'; // your user ID or unique session key to hold cart items
$configCart = require('/configCart.php'); // the file contains cart configuration

$cart = new Cart(
  $session,
  $instanceName,
  $session_key,
  $configCart
);

许可协议

Laravel 购物车是开源软件,许可协议为 MIT 许可协议