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

Eprel Api Client Laravel Package

asm/eprel-api-client

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require asm/eprel-api-client
    
  2. Basic initialization (uses Guzzle and Symfony HTTP clients by default):
    use Asm\EprelApiClient\EprelClient;
    
    $client = new EprelClient();
    
  3. First API call (search for products):
    $results = $client->search()->byProductType('refrigerator')->execute();
    

Key Entry Points

  • Search API: $client->search() → Fluent builder for queries.
  • Product API: $client->product($productId) → Fetch single product details.
  • Cache: Built-in PSR-6 cache support (optional but recommended for production).

Implementation Patterns

1. Fluent Query Building

Use the fluent interface for complex searches:

$client->search()
    ->byProductType('washing_machine')
    ->byEnergyLabel('A')
    ->byEnergyEfficiencyClass('A+++')
    ->byManufacturer('Bosch')
    ->limit(10)
    ->execute();

2. Integration with Laravel

  • Service Provider: Register the client in AppServiceProvider:
    public function register()
    {
        $this->app->singleton(EprelClient::class, function ($app) {
            return new EprelClient(
                httpClient: $app->make(\GuzzleHttp\Client::class),
                cache: $app->make(\Illuminate\Contracts\Cache\Store::class)
            );
        });
    }
    
  • Dependency Injection: Inject EprelClient into controllers/services:
    public function __construct(private EprelClient $eprel)
    {
    }
    

3. Handling Responses

  • Paginated Results: Use ->nextPage() or iterate with ->getIterator().
  • Data Transformation: Extend the client or use Laravel’s map:
    $products = $this->eprel->search()->execute()->map(fn ($item) => [
        'id' => $item['productId'],
        'name' => $item['productName'],
    ]);
    

4. Caching Strategies

  • Automatic Caching: Enable via constructor:
    $client = new EprelClient(cache: $cacheStore, cacheTTL: 3600);
    
  • Manual Cache Invalidation: Clear cache when product data changes:
    $cache->forget('eprel_product_' . $productId);
    

5. Error Handling

  • HTTP Errors: Use try/catch with EprelApiException:
    try {
        $client->product('123')->execute();
    } catch (EprelApiException $e) {
        report($e); // Log or notify
    }
    
  • Rate Limiting: Implement exponential backoff for 429 responses.

Gotchas and Tips

Pitfalls

  1. API Rate Limits:

  2. Deprecated Endpoints:

    • The package may not cover all EPREL endpoints. Check the EPREL API docs for unsupported features.
  3. Type Safety:

    • The client returns arrays by default. Use PHP 8.4’s array_key_first/array_key_exists carefully or extend the client to return DTOs:
      class ProductDto {
          public function __construct(
              public string $productId,
              public string $productName,
              public ?string $energyLabel,
          ) {}
      }
      
  4. Cache Key Collisions:

    • Default cache keys are prefixed with eprel_. Customize if using shared cache (e.g., Redis):
      $client = new EprelClient(cache: $cache, cachePrefix: 'myapp_eprel_');
      

Debugging Tips

  • Enable HTTP Logging:
    $client = new EprelClient(httpClient: new \GuzzleHttp\Client([
        'handler' => \GuzzleHttp\HandlerStack::create([
            new \GuzzleHttp\Middleware::tap(function ($request) {
                \Log::debug('EPREL Request:', ['url' => (string) $request->getUri()]);
            }),
        ]),
    ]));
    
  • Validate API Responses: Use json_last_error() to debug malformed responses:
    $response = $client->search()->execute();
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new \RuntimeException('Invalid JSON response');
    }
    

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client for features like:

    • Custom headers (e.g., Accept: application/vnd.eprel.v1+json).
    • Proxy support.
  2. Add Endpoints: Extend the client to support unsupported EPREL endpoints:

    class CustomEprelClient extends EprelClient {
        public function getProductDocuments(string $productId): array {
            return $this->request('GET', "/products/{$productId}/documents");
        }
    }
    
  3. Mocking for Tests: Use Laravel’s MockHttp or a custom PSR-18 client:

    $mockHandler = \Mockery::mock();
    $mockHandler->shouldReceive('send')
        ->andReturn(new \GuzzleHttp\Psr7\Response(200, [], '{"data": []}'));
    
    $client = new EprelClient(httpClient: new \GuzzleHttp\Client([
        'handler' => new \GuzzleHttp\HandlerStack($mockHandler),
    ]));
    
  4. Webhook Integration: Poll for updates using ->search()->byLastUpdatedAfter($timestamp) and trigger webhooks on changes.

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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours