Weave 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

Batteryincluded Php Sdk Laravel Package

batteryincluded/batteryincluded-php-sdk

The official PHP SDK for the BatteryIncluded API. Requires PHP 8.2+, installs via Composer, and lets you sync products and other resources, with extensible DTOs for adding custom shop-specific fields.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require batteryincluded/batteryincluded-php-sdk
    

    Ensure your project uses PHP 8.2+.

  2. First Use Case: Sync a Product

    use BatteryIncludedSdk\Dto\ProductBaseDto;
    use BatteryIncludedSdk\Client\ApiClient;
    use BatteryIncludedSdk\Client\CurlHttpClient;
    use BatteryIncludedSdk\Service\SyncService;
    
    $product = new ProductBaseDto('1');
    $product->setName('Test Product');
    $product->setPrice(19.99);
    
    $apiClient = new ApiClient(
        new CurlHttpClient(),
        'https://api.batteryincluded.io/api/v1/collections/',
        'YOUR_COLLECTION_ID',
        'YOUR_API_KEY'
    );
    
    $syncService = new SyncService($apiClient);
    $result = $syncService->syncFullElements($product);
    
  3. Where to Look First

    • Examples Directory: Explore examples/ for ready-to-use workflows (e.g., sync_full_product_and_blogs.php).
    • API Documentation: Refer to Postman docs for endpoint details.
    • DTO Classes: Check Dto/ for base classes (ProductBaseDto, BlogBaseDto) to extend.

Implementation Patterns

Core Workflows

  1. Syncing Data

    • Use SyncService for full updates (syncFullElements) or partial updates (syncPartialElements).
    • Batch sync multiple documents in a single request:
      $syncService->syncFullElements($product1, $product2, $blog);
      
  2. Searching and Browsing

    • Use BrowseService with BrowseSearchStruct for queries:
      $searchStruct = new BrowseSearchStruct();
      $searchStruct->setQuery('laptop');
      $searchStruct->addFilter('type', 'PRODUCT');
      
      $results = $browseService->browse($searchStruct);
      
  3. Extending DTOs

    • Subclass ProductBaseDto or BlogBaseDto to add custom fields:
      class CustomProductDto extends ProductBaseDto {
          private ?string $material;
      
          public function jsonSerialize(): array {
              return array_merge_recursive(
                  parent::jsonSerialize(),
                  ['_PRODUCT' => ['material' => $this->material]]
              );
          }
      }
      
  4. Mixed Collections

    • Sync heterogeneous data (products + blogs) in one collection:
      $syncService->syncFullElements($product, $blog);
      
    • Filter results by type:
      $searchStruct->addFilter('type', 'BLOG');
      

Integration Tips

  • Error Handling: Wrap API calls in try-catch blocks to handle HTTP/validation errors:
    try {
        $result = $syncService->syncFullElements($product);
    } catch (\Exception $e) {
        \Log::error('Sync failed: ' . $e->getMessage());
    }
    
  • Rate Limiting: Monitor API response headers for X-RateLimit-* to avoid throttling.
  • Environment Config: Store API_KEY and COLLECTION_ID in Laravel’s .env:
    BATTERYINCLUDED_API_KEY=your_key_here
    BATTERYINCLUDED_COLLECTION_ID=your_collection_id
    
    Then inject them via config or service container.

Gotchas and Tips

Pitfalls

  1. Null Field Handling

    • Custom fields must explicitly filter out null values in jsonSerialize() to avoid sending empty keys:
      array_filter($jsonDto, static fn($value) => $value !== null)
      
    • Omitting this may cause API validation errors.
  2. ID Collisions

    • Mixed collections use prefixed IDs (e.g., PRODUCT-1, BLOG-1). Ensure your local IDs are unique per type to avoid conflicts.
  3. Type-Specific Field Access

    • Always check the type field before accessing nested data (_PRODUCT, _BLOG):
      if ($document['type'] !== 'PRODUCT') {
          throw new \InvalidArgumentException('Expected PRODUCT type');
      }
      
  4. API Key Permissions

    • Ensure your API key has write permissions for the collection. Test with syncPartialElements first to avoid full overwrites.

Debugging

  • Enable HTTP Logging
    • Extend CurlHttpClient to log requests/responses:
      class DebugHttpClient extends CurlHttpClient {
          public function request(string $method, string $url, array $data = []): array {
              \Log::debug('Request: ' . json_encode(compact('method', 'url', 'data')));
              $response = parent::request($method, $url, $data);
              \Log::debug('Response: ' . json_encode($response));
              return $response;
          }
      }
      
  • Validate DTOs
    • Use Laravel’s validation rules to sanitize data before syncing:
      $validated = $request->validate([
          'name' => 'required|string|max:255',
          'price' => 'required|numeric|min:0',
      ]);
      $product->setName($validated['name']);
      

Extension Points

  1. Custom HTTP Clients

    • Replace CurlHttpClient with Guzzle or Symfony’s HttpClient for advanced features (retries, middleware):
      use Symfony\Contracts\HttpClient\HttpClientInterface;
      
      $httpClient = \Symfony\Contracts\HttpClient\HttpClient::create();
      $apiClient = new ApiClient($httpClient, ...);
      
  2. Event Dispatching

    • Trigger Laravel events after sync operations:
      event(new ProductSynced($product, $result));
      
    • Listen for sync results in EventServiceProvider.
  3. Queue Sync Jobs

    • Offload heavy syncs to queues:
      SyncProductJob::dispatch($product)->onQueue('batteryincluded');
      
    • Implement ShouldQueue interface for SyncService.
  4. Webhook Integration

    • Use Laravel’s webhook package to listen for BatteryIncluded webhooks (e.g., sync confirmation):
      Route::post('/batteryincluded-webhook', [WebhookController::class, 'handle']);
      

Config Quirks

  • Base URL Overrides
    • The SDK hardcodes api/v1/collections/. Override via dependency injection:
      $apiClient = new ApiClient($httpClient, 'https://custom-api.batteryincluded.io/v2/collections/');
      
  • Collection Defaults
    • If your collection uses a non-standard endpoint (e.g., /shops/{id}/collections), extend ApiClient to support path parameters.

Performance Tips

  • Batch Processing
    • Sync up to 100 documents per request to minimize API calls.
  • Partial Updates
    • Use syncPartialElements for incremental updates (e.g., stock changes) instead of full syncs.
  • Caching Search Results
    • Cache BrowseService responses in Laravel’s cache:
      $cacheKey = 'batteryincluded_search_' . md5($searchStruct->getQuery());
      return Cache::remember($cacheKey, now()->addHours(1), fn() => $browseService->browse($searchStruct));
      
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.
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table