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

Configurator Api Laravel Package

configuratorware/configurator-api

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require configuratorware/configurator-api
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Configuratorware\ConfiguratorApi\ConfiguratorApiServiceProvider::class,
    ],
    
  2. Publish Config

    php artisan vendor:publish --provider="Configuratorware\ConfiguratorApi\ConfiguratorApiServiceProvider" --tag="config"
    

    This generates config/configurator-api.php. Update with your API endpoint, API key, and default options.

  3. First Use Case: Fetching a Product Configuration

    use Configuratorware\ConfiguratorApi\Facades\ConfiguratorApi;
    
    $productId = 'prod_123';
    $config = ConfiguratorApi::getProductConfig($productId);
    
    // Handle response (success/error)
    if ($config->isSuccess()) {
        $data = $config->getData();
        // Process configuration data
    } else {
        $error = $config->getError();
        // Log or handle error
    }
    

Key Configuration Options

  • api_endpoint: Base URL for the configurator API.
  • api_key: Authentication key (use environment variables for security).
  • timeout: Default request timeout (e.g., 30 seconds).
  • debug: Enable/disable debug logging.

Initialization Check

Verify the API connection with:

php artisan configurator-api:test

This runs a health check against the configured endpoint.


Implementation Patterns

Common Workflows

1. Product Configuration Retrieval

// Fetch full configuration for a product
$config = ConfiguratorApi::getProductConfig($productId);

// Fetch specific rules (e.g., pricing, compatibility)
$rules = ConfiguratorApi::getProductRules($productId, ['pricing', 'compatibility']);

2. Real-Time Validation

Validate user selections before submission:

$selections = [
    'option_1' => 'value_a',
    'option_2' => 'value_b',
];

$validation = ConfiguratorApi::validateSelections($productId, $selections);

if ($validation->isValid()) {
    // Proceed to checkout
} else {
    $errors = $validation->getErrors();
    // Show errors to user
}

3. Caching Strategies

Leverage Laravel’s cache to reduce API calls:

$config = Cache::remember("config_{$productId}", now()->addHours(1), function () use ($productId) {
    return ConfiguratorApi::getProductConfig($productId);
});

4. Event-Driven Updates

Use Laravel events to sync configuration changes:

// In a service or controller
event(new \Configuratorware\ConfiguratorApi\Events\ConfigUpdated($productId, $newConfig));

// Listen in EventServiceProvider
protected $listen = [
    \Configuratorware\ConfiguratorApi\Events\ConfigUpdated::class => [
        \App\Listeners\SyncProductConfig::class,
    ],
];

5. Integration with Eloquent Models

Attach configurations to a Product model:

namespace App\Models;

use Configuratorware\ConfiguratorApi\Facades\ConfiguratorApi;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function getConfiguration()
    {
        return Cache::remember("config_{$this->id}", now()->addHours(1), function () {
            return ConfiguratorApi::getProductConfig($this->id);
        });
    }
}

Integration Tips

API Rate Limiting

  • Implement a queue for bulk operations to avoid hitting rate limits:
    ConfiguratorApi::dispatchSyncProductConfig($productId)->onQueue('configurator');
    

Retry Logic

Use Laravel’s retry mechanism for transient failures:

$config = ConfiguratorApi::withRetry(3, 1000)->getProductConfig($productId);

Webhook Listeners

Listen for configuration updates via webhooks:

Route::post('/config-webhook', function (Request $request) {
    $payload = $request->json()->all();
    ConfiguratorApi::handleWebhook($payload);
});

Testing

Mock the API in tests using Laravel’s HTTP testing:

$response = Http::fake([
    'configurator-api.example.com/*' => Http::response(['data' => 'mock'], 200),
]);

$config = ConfiguratorApi::getProductConfig('test_123');
$config->assertSuccess();

Gotchas and Tips

Pitfalls

1. API Key Exposure

  • Risk: Hardcoding API keys in config/configurator-api.php.
  • Fix: Use Laravel’s .env:
    CONFIGURATOR_API_KEY=your_secure_key_here
    
    Then reference it in config:
    'api_key' => env('CONFIGURATOR_API_KEY'),
    

2. Caching Invalidation

  • Risk: Stale cached configurations if the API updates externally.
  • Fix: Implement a cache tag or use Cache::forget() in webhook listeners.

3. Timeout Errors

  • Risk: Slow API responses causing timeouts.
  • Fix: Increase timeout in config or implement async processing:
    'timeout' => 60, // seconds
    

4. Rate Limiting

  • Risk: Exceeding API rate limits during bulk operations.
  • Fix: Use queues and exponential backoff:
    ConfiguratorApi::withRetry(5, 2000)->getProductConfig($productId);
    

5. Data Mismatch

  • Risk: API response structure changes breaking your code.
  • Fix: Use defensive programming:
    $data = $config->getData() ?? [];
    $price = $data['price'] ?? null;
    

Debugging Tips

Enable Debug Mode

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

Logs requests/responses to storage/logs/configurator-api.log.

Inspect Raw Responses

$response = ConfiguratorApi::getProductConfig($productId);
if ($response->isError()) {
    \Log::debug('Raw response:', $response->getRawResponse());
}

Common Error Codes

Code Description Solution
401 Invalid API key Check .env and API key permissions.
404 Product not found Validate $productId format.
429 Rate limit exceeded Implement retries or queue the request.
500 Server error Contact API support; check logs.

Extension Points

Custom Request Transformers

Override response handling:

ConfiguratorApi::extend(function ($client) {
    $client->extend('transform', function ($response) {
        $data = $response->json();
        return collect($data)->when(
            $data['type'] === 'error',
            fn ($c) => $c->merge(['custom_field' => 'value'])
        );
    });
});

Middleware for Requests

Add headers or modify requests globally:

ConfiguratorApi::extend(function ($client) {
    $client->getMiddleware()->prepend(
        \Configuratorware\ConfiguratorApi\Middleware\AddCustomHeader::class
    );
});

Event Extensions

Listen for API events to trigger custom logic:

ConfiguratorApi::on('config.fetched', function ($productId, $config) {
    // Trigger analytics or sync to another service
});

Local Overrides

Override API endpoints for local development:

if (app()->environment('local')) {
    ConfiguratorApi::setEndpoint('http://configurator-api.local');
}
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware