unisharp/pricing

Buyable的模块化定价包。

dev-master / 1.0.x-dev 2018-07-02 02:37 UTC

This package is auto-updated.

Last update: 2024-09-13 22:20:29 UTC


README

Latest Version on Packagist Software License Build Status Coverage Status Quality Score Total Downloads

Buyable的模块化定价包。

安装

composer require unisharp/pricing dev-master

配置

php artisan vendor:publish --tag pricing

config/pricing.php中设置可用的定价模块。

return [
    'modules' => [
        UniSharp\Pricing\Tests\Fixtures\TestModule::class,
    ]
];

模块原则

  • 模块必须实现UniSharp\Pricing\ModuleContract接口,该接口需要实现handlefinish函数。
  • 模块将按照config/pricing.php中的顺序进行处理,第一个模块将处理定价逻辑并将定价实例传递给下一个模块(管道模式)。
  • 定价模块在handle函数中可以调用的一些API
    • $pricing->addFee(int $fee);
    • $pricing->addDeduction(int $deduction);
    • $pricing->writeModuleLog(mix $log);
    • $pricing->getModuleInfo();

addFeeaddDeductionwriteModuleLog将仅更改定价实例的属性。getModuleInfo可以获取该模块的额外信息。

  • 定价执行后将会调用finish函数。模块成功应用后的逻辑可以在此处实现。
namespace UniSharp\Pricing\Tests\Fixtures;

use Closure;
use UniSharp\Pricing\Pricing;
use UniSharp\Pricing\ModuleContract;
use Illuminate\Contracts\Pipeline\Pipeline;

class TestModule implements ModuleContract
{
    const FEE = 99;
    const DEDUCTION = 88;
    const LOG = 'log';

    public function handle(Pricing $pricing, Closure $next)
    {
        $pricing->addFee(static::FEE);
        $pricing->addDeduction(static::DEDUCTION);
        $pricing->writeModuleLog(static::LOG);

        $info = $pricing->getModuleInfo();

        return $next($pricing);
    }

    public function finish(Pricing $pricing)
    {
        //
    }
}

定价用法

use UniSharp\Pricing\Facades\Pricing;

class Foo {
    // set items and get original price
    Pricing::setItems(UniSharp\Cart\CartItemCollection $items)
        ->getOriginalTotal();

    // apply some modules
    Pricing::apply(ModuleA::class)
        ->apply(ModuleB::class);
    
    // apply some modules with some extra info
    Pricing::apply(ModuleA::class)
        ->apply(ModuleB::class)
        ->with([
            ModuleA::class => 'extra info A',
            ModuleB::class => 'extra info B',
        ]);
    
    // apply modules and get final total
    Pricing::apply(ModuleA::class)
        ->apply(ModuleB::class)
        ->getTotal();

    // apply modules and execute them
    Pricing::apply(ModuleA::class)
        ->apply(ModuleB::class)
        ->execute();
    
    // get all applied modules
    Pricing::getAppliedModules();

    // get all fees
    Pricing::getFees();

    // get fee of a specific module
    Pricing::getFee(ModuleA::class);
    
    // get all deductions
    Pricing::getDeductions();

    // get deduction of a specific module
    Pricing::getDeduction(ModuleA::class);

    // get items
    Pricing::getItems();
}