Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Pricing Engine Laravel Package

php-junior/pricing-engine

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require php-junior/pricing-engine
    php artisan vendor:publish --provider="PhpJunior\PricingEngine\Providers\PricingEngineServiceProvider"
    php artisan migrate
    
    • Verify config/pricing-engine.php is published and updated if needed (e.g., model/table names).
  2. First Use Case: Apply a Discount

    use PhpJunior\PricingEngine\Facades\PricingEngine;
    
    $finalPrice = PricingEngine::make()->applyRules(
        basePrice: 100.00,
        context: ['user_id' => 1, 'product_id' => 101]
    );
    
    • Context: Pass dynamic data (e.g., user_id, product_id, cart_total) to evaluate rules.

Implementation Patterns

Core Workflows

  1. Defining Rules via Facade

    PricingEngine::make()->savePricingRule(
        name: 'Black Friday 20%',
        priority: 10,
        conditions: [
            new ConditionData('date', 'between', ['2025-11-20', '2025-11-25']),
            new ConditionData('user.role', 'in', ['premium', 'vip'])
        ],
        actions: [
            new ActionData('discount', 20) // 20% discount
        ]
    );
    
    • Priority: Lower numbers = higher priority (configurable in config/pricing-engine.php).
  2. Dynamic Context Evaluation

    $context = [
        'user' => auth()->user(),
        'cart' => $cart->load('items'),
        'date' => now()->format('Y-m-d')
    ];
    $price = PricingEngine::make()->applyRules(99.99, $context);
    
    • Nested Data: Use dot notation (user.role) to access nested objects/arrays.
  3. Rule Groups (Composite Rules)

    PricingEngine::make()->savePricingRuleGroup(
        name: 'Seasonal Promotions',
        rules: [1, 2, 3] // IDs of pre-defined rules
    );
    
    • Apply groups via applyRuleGroup($groupId, $context).
  4. Testing Rules

    $rule = PricingEngine::make()->getRule(1);
    $isApplicable = $rule->evaluate($context);
    
    • Useful for debugging or pre-checking before applying.

Integration Tips

  • Event-Based Triggers: Hook into OrderCreated or CartUpdated events to re-evaluate pricing dynamically.
    event(new OrderCreated($order));
    // Inside listener:
    $order->final_price = PricingEngine::make()->applyRules($order->base_price, $order->context);
    
  • API Responses: Cache evaluated prices in the response (e.g., data.price_after_rules).
  • Admin Panel: Build a UI to manage rules via Laravel Nova or Filament:
    // Example Nova Tool
    Nova::tools([
        new PricingRuleManager,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Context Mismatches

    • Issue: Rules fail silently if context keys don’t match (e.g., user_id vs. user.id).
    • Fix: Use dd($context) to verify keys before applying rules.
  2. Priority Conflicts

    • Issue: Overlapping rules with same priority may not behave as expected.
    • Fix: Explicitly set priorities (e.g., priority: 1 for VIP, priority: 10 for seasonal).
  3. Circular Dependencies

    • Issue: Rules referencing each other (e.g., Rule A applies discount, Rule B checks for discount) can cause infinite loops.
    • Fix: Use applyRules() with a maxIterations parameter (if supported) or refactor logic.
  4. Database Locks

    • Issue: High-traffic sites may hit locks during savePricingRule().
    • Fix: Batch updates or use queue jobs:
      PricingEngine::make()->queueRuleUpdate($ruleData);
      

Debugging

  • Log Evaluation Steps Enable debug mode in config:

    'debug' => env('PRICING_ENGINE_DEBUG', false),
    

    Logs will show which rules were evaluated and why they passed/failed.

  • Rule Validation Use the validateRule() method to check syntax before saving:

    $errors = PricingEngine::make()->validateRule($ruleData);
    if ($errors) throw new \Exception($errors);
    

Extension Points

  1. Custom Operators/Actions Extend the package by registering new operators (e.g., contains) or actions (e.g., free_shipping):

    // config/pricing-engine.php
    'operators' => [
        'contains' => \PhpJunior\PricingEngine\Operators\ContainsOperator::class,
    ],
    'actions' => [
        'free_shipping' => \App\Actions\FreeShippingAction::class,
    ],
    
  2. Model Binding Bind custom models for rules/conditions:

    // config/pricing-engine.php
    'models' => [
        'rule' => \App\Models\CustomPricingRule::class,
    ],
    
  3. Caching Strategies Cache evaluated rules for performance:

    Cache::remember("pricing_rules_{$contextHash}", now()->addHours(1), function() {
        return PricingEngine::make()->getAllRules();
    });
    
  4. Localization Support multi-language rule names/descriptions by extending the Rule model:

    use Spatie\Translatable\HasTranslations;
    class CustomPricingRule extends Model implements HasTranslations {
        public $translatable = ['name', 'description'];
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor