mmdm / sim-cart
一个简单而优雅的购物车库
Requires
- ext-json: *
- ext-pdo: *
- mmdm/sim-cookie: ^3.0
README
这是一个用于购物车管理的简单库。
安装
composer
composer require mmdm/sim-cart
或者你可以从github下载zip文件并解压,然后将文件放到你的项目库中,像使用其他库一样使用它。
只需添加以下行来自动加载文件
require_once 'path_to_library/autoloader.php';
然后你就可以开始了。
特性
-
多购物车管理
-
简单购物车管理
-
这不仅仅是一个简单的购物车,它还有一些结构来创建一个简单而优雅的在线商店。
架构
该库使用数据库以获得最佳性能
排序规则
应该是 utf8mb4_unicode_ci
,因为它是一个非常不错的排序规则。关于 utf8
和 utf8mb4
在 general
和 unicode
之间的差异,请参阅 这个链接,来自 stackoverflow
表
-
users
该表包含所有用户。
该表至少应包含以下列
- id (INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT)
-
products
该表包含所有产品。
该表至少应包含以下列
- id (INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT)
-
product_property
该表包含所有产品的属性。
该表至少应包含以下列
-
id (INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT)
-
code (VARCHAR(20) NOT NULL)
-
product_id (INT(11) UNSIGNED NOT NULL)
-
stock_count (INT(11) UNSIGNED NOT NULL)
-
max_cart_count (INT(11) UNSIGNED NOT NULL)
-
price (BIGINT(20) UNSIGNED NOT NULL)
-
discounted_price (BIGINT(20) UNSIGNED NOT NULL)
-
tax_rate (DECIMAL (5, 2) UNSIGNED NOT NULL DEFAULT 0)
-
is_available (TINYINT(1) UNSIGNED NOT NULL DEFAULT 1)
约束
-
添加约束 UC_Code UNIQUE (code)
-
添加约束 fk_pp_p FOREIGN KEY(product_id) REFERENCES products(id) ON DELETE CASCADE ON UPDATE CASCADE
-
-
carts
该表包含所有购物车。
该表至少应包含以下列
-
id (INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT)
-
user_id (INT(11) UNSIGNED NOT NULL)
-
name (VARCHAR(255) NOT NULL)
-
created_at (INT(11) UNSIGNED NOT NULL)
-
expire_at (INT(11) UNSIGNED NOT NULL)
约束
- 添加约束 UC_UserID UNIQUE (user_id,name)
-
-
cart_item
该表包含所有购物车项目。
该表至少应包含以下列
-
id (INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT)
-
cart_id (INT(11) UNSIGNED NOT NULL)
-
product_property_id (INT(11) UNSIGNED NOT NULL)
-
qnt (INT(11) UNSIGNED NOT NULL)
约束
-
添加约束 fk_ci_c FOREIGN KEY(cart_id) REFERENCES carts(id) ON DELETE CASCADE ON UPDATE CASCADE
-
添加约束 fk_ci_pp FOREIGN KEY(product_property_id) REFERENCES product_property(id) ON DELETE CASCADE ON UPDATE CASCADE
-
如何使用
首先,你需要一个如下的 PDO
连接
$host = '127.0.0.1'; $db = 'database name'; $user = 'username'; $pass = 'password'; // this is very nice collation to use $charset = 'utf8mb4'; $dsn = "mysql:host={$host};dbname={$db};charset={$charset}"; $options = [ // add this option to show exception on any bad condition PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); }
然后你需要一个如下的 cookie
类
$cookieStorage = new \Sim\Cookie\Cookie();
[可选但强烈推荐] 你需要两个密钥来保护存储在cookie中的数据。这两个密钥应该是两个base64编码的字符串。只需生成两个密码并将它们编码为base64字符串。有关这两个密钥的更多信息,请参阅 这个链接
// this is what you have for protecting your data $cookieStorage = new \Sim\Cookie\Cookie( new \Sim\Crypt\Crypt( $mainCryptKey, $assuredCryptKey ) );
实例化购物车库
$cookieStorage = new \Sim\Cookie\Cookie(new \Sim\Crypt\Crypt($mainCryptKey, $assuredCryptKey)); // we don't need a user, so we don't pass it $cart = new \Sim\Cart\Cart($pdo, $cookieStorage); // use cart methods $cart->add('product_code');
购物车方法
setCartName(string $name)
你可以给你的购物车命名。这将用于你想要在数据库中存储购物车的情况。默认名称是 default
。
getCartName(): string
获取购物车的名称。
setExpiration(int $expire_time)
注意:你需要发送购物车到期的持续时间,例如 86400
,即 1 天
的秒数。在调用 store
方法后,当前时间将添加到这个过期时间。
注意:你必须知道这个过期时间与数据库字段中的过期时间不同。
设置购物车过期时间。
getExpiration(): int
获取购物车过期时间。默认过期时间为31536000
,即1年
。
注意:此方法仅返回时间,如31536000
,即1年
,而不是过期时间,如果需要知道过期时间,请将购物车存储到数据库并获取购物车的expire_at
字段。
utils(): ICartsUtil
可用于当前购物车和当前用户的工具。
有关此工具的信息,请参阅CartUtil部分。
注意:此功能仅在使用pdo连接和用户ID时才有效。
add(string $item_code, array $item_info = null)
使用从product_property
表中的产品代码添加项目到购物车。您可以使用$item_info
参数向项目添加额外信息。最后存储的项目具有product_property
表的列字段值、qnt
参数以及您的额外信息。
注意:所有项目的键都是配置文件中的键,并且在配置文件中也有注释,请勿更改键。
注意:默认情况下,项目不会存储在cookie中,您应该使用store
方法自行操作。
update(string $item_code, array $item_info = null)
类似于add
方法,具有额外的功能,即检查项目是否已添加,如果未添加,则内部添加。
remove(string $item_code): bool
从购物车中删除项目。
getItem(string $item_code): array
获取购物车中的特定项目。
getItems(): array
获取购物车中的所有项目。
clearItems()
从购物车中删除所有项目。
hasItemWithCode(string $item_code): bool
检查购物车中是否已设置项目。
totalPrice(): float
获取项目总价。
totalDiscountedPrice(): float
获取项目折扣价总和。
totalPriceWithTax(): float
获取考虑每个项目税项的总价。
totalDiscountedPriceWithTax(): float
获取考虑每个项目税项的折扣价总和。
totalAttributeValue(string $key): float
获取所有项目中特定键的总和。
discountedPercentage(string $item_code, int $decimal_numbers = 2, bool $round = false): float
获取特定项目的折扣百分比。
totalDiscountedPercentage(int $decimal_numbers = 2, bool $round = false): float
获取所有项目的折扣百分比。
totalDiscountedPercentageWithTax(int $decimal_numbers = 2, bool $round = false): float
考虑每个项目的税项后获取所有项目的折扣百分比。
store()
将购物车项目存储到存储(cookie)中。
restore()
从存储(cookie)中恢复购物车项目到购物车项目。
destroy()
从存储(cookie)中销毁购物车。
CartUtil方法
实例化
如果您需要在外部实例化工具(您不需要这样做)
$utils = new CartsUtil( PDO $pdo_instance, ICart &$cart, ?int $user_id, ?array $config = null );
runConfig()
创建表结构。
getCart(): ICart
获取类中使用的购物车。
setUserId(int $user_id)
将用户ID设置为用于数据库的工作。
getUserId(): int
获取使用的用户ID。
save(int $max_stored_cart = PHP_INT_MAX, array $extra_parameters = [], string $extra_where = null, array $bind_values = []): bool
将购物车保存到数据库。
您可以指定特定用户可以存储在数据库中的购物车数量。您还可以传递额外参数和参数化where子句以自定义存储(表为carts
)。
注意:您应使用实际的购物车表列名。
注意:以下列将取消设置并使用购物车信息
-
user_id
-
name
-
created_at
// simple usage (unnecessary) $cartUtil->save( 2, // max stored cart count [ 'extra_column' => extra value, ... ], "some_extra_where=:extra_where_param1", [ 'extra_where_param1' => actual value ] ); // if you want use from cart $cart->utils()->save( 2, // max stored cart count [ 'extra_column' => extra value, ... ], "some_extra_where=:extra_where_param1", [ 'extra_where_param1' => actual value ] )
要获取最大存储购物车数量的异常和数据库错误,请在try {...} catch() {...}
块中放置您的代码
try { // try to save or other thing // ... $cart->utils()->save(1); } catch (\Sim\Cart\Exceptions\CartMaxCountException $e) { // if cart count is at maximum count of it // ... } catch (\Sim\Cart\Interfaces\IDBException $e) { // database error // ... } catch (\Sim\Crypt\Exceptions\CryptException $e) { // encryption or decryption has error // ... }
fetch(bool $append_to_previous_items = false)
从数据库中获取购物车项并将它们存储到提供的购物车类中。
注意:它会先删除所有项,如果您想防止这种默认行为,请将true
作为第二个参数发送。
delete(string $cart_name): bool
删除特定用户的特定购物车。
deleteExpiredCarts(string $cart_name): bool
删除特定用户的过期的购物车。
changeName(string $old_cart_name, string $new_cart_name): bool
将特定用户的购物车名称从旧名称
更改为新名称
。
getItem(string $item_code, $columns = '*'): array
获取具有特定列的特定项。
getStockCount(string $item_code): int
获取特定物品的库存数量。
getMaxCartCount(string $item_code): int
获取特定物品的最大购物车数量。
示例
创建所有表
// after instantiate cart class or even cart util class, // you can use util's methods. For convenient in examples, // we will use cart class utils $cart->utils()->runConfig();
将项目添加到购物车
$cart->add('item_id_from_product_property'); // with extra information $cart->add('item_id_from_product_property', [ 'type' => 'service', ... ]);
更新购物车中的项目
非常重要提示:您不能更改数据库中已有值的项值。只能更改数量和您的额外信息。
// keys are from product_property in // config NOT actual column of table $cart->update('item_id_from_product_property', [ 'qnt' => 4 ]);
购物车和存储
// store cart items in cookie $cart->store(); // restore cart items $cart->restore(); // delete and destroy cookie for cart $cart->destroy();
报告
echo 'total price: ' . $cart->totalPrice() . PHP_EOL; echo 'total price with tax: ' . $cart->totalPriceWithTax() . PHP_EOL; echo 'total discount price: ' . $cart->totalDiscountedPrice() . PHP_EOL; echo 'total discount price with tax: ' . $cart->totalDiscountedPriceWithTax() . PHP_EOL; echo 'discount percentage specific item: ' . $cart->discountedPercentage('item_id_from_product_property') . PHP_EOL; echo 'total discount percentage: ' . $cart->totalDiscountedPercentage() . PHP_EOL; echo 'total discount percentage with tax: ' . $cart->totalDiscountedPercentageWithTax() . PHP_EOL; echo 'total rounded discount percentage: ' . $cart->totalDiscountedPercentage(2, true) . PHP_EOL; echo 'total rounded discount percentage with tax: ' . $cart->totalDiscountedPercentageWithTax(2, true) . PHP_EOL;
依赖项
这里有一些依赖项,包括
Crypt 库。使用此功能,如果发生任何会话/cookie篡改,他们无法看到实际数据,因为这些数据是加密的。
Cookie 库来操作cookies。
许可
在MIT许可下