编程

基于Laravel的一个简单钱包实现

1018 2022-05-29 10:03:55

Laravel Wallet 是 Stephen Jude 出品的一个针对Laravel模型实现的简单钱包:

class User extends Authenticatable implements Wallet
{
    use HasWallet;
}

使用 HasWallet trait,你可以增加储蓄,提现,以及查看钱包余额:

// Making deposits
 
// returns the wallet balance: 200.22
$user->deposit(200.22);
 
// returns the wallet balance: 400.22
$user->deposit(200);

从上例的钱包余额中,你可以提现:

// returns the wallet balance: 200.22
$user->withdraw(200);
 
// returns the wallet balance: 200
$user->withdraw(0.22);

如果你尝试提现的金额超过了钱包金额,会抛出异常:

use Stephenjude\Wallet\Exceptions\ InsufficientFundException;
 
try {
    $user->withdraw(5_000);
} catch (InsufficientFundException $e) {
    // Code to handle insufficient funds...
}

安装

composer require stephenjude/laravel-wallet