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

Insig Aws Bundle Laravel Package

damonjones/insig-aws-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require damonjones/insig-aws-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        DamonJones\InsigAWSBundle\InsigAWSBundle::class => ['all' => true],
    ];
    
  2. Configure AWS Credentials Add to config/packages/insig_aws.yaml (or config.yml in Symfony 3.x):

    insig_aws:
        client:
            access_key_id:     "%env(AWS_ACCESS_KEY_ID)%"
            secret_access_key: "%env(AWS_SECRET_ACCESS_KEY)%"
    
  3. First Use Case: Item Lookup Inject the client via dependency injection or fetch it from the container:

    use Insig\AWSBundle\Request\ItemLookupRequest;
    
    class ProductService {
        public function __construct(private readonly Insig\AWSBundle\Client $client) {}
    
        public function getProductDetails(string $asin): array {
            $request = new ItemLookupRequest();
            $request->setASIN($asin);
            $response = $this->client->execute($request);
            return $response->asArray()['Items']['Item'];
        }
    }
    

Implementation Patterns

Common Workflows

  1. Request Types The bundle supports multiple AWS Product Advertising API requests out-of-the-box:

    • ItemLookupRequest (for product details by ASIN/ISBN)
    • ItemSearchRequest (for product searches by keyword)
    • CartCreateRequest (for creating shopping carts)
    • CartModifyRequest (for updating carts)
    • CartGetRequest (for retrieving carts)

    Example search:

    $searchRequest = new ItemSearchRequest();
    $searchRequest->setKeywords('Laravel books')
                  ->setSearchIndex('Books')
                  ->setResponseGroup('Medium');
    $results = $this->client->execute($searchRequest);
    
  2. Response Handling Responses can be parsed as:

    • XML (default): $response->asXml()
    • Array: $response->asArray()
    • SimpleXML: $response->asSimpleXml()

    Example with XML:

    $xml = $response->asXml();
    $title = $xml->Items->Item->ItemAttributes->Title;
    
  3. Dependency Injection Prefer injecting the Insig\AWSBundle\Client interface into services:

    public function __construct(
        private readonly Client $awsClient,
        private readonly LoggerInterface $logger
    ) {}
    
  4. Error Handling Wrap API calls in try-catch blocks:

    try {
        $response = $this->client->execute($request);
    } catch (\Insig\AWSBundle\Exception\AwsException $e) {
        $this->logger->error('AWS API Error', ['error' => $e->getMessage()]);
        throw new \RuntimeException('Failed to fetch product data', 0, $e);
    }
    
  5. Caching Responses Cache responses to avoid rate limits or repeated API calls:

    $cacheKey = 'aws_product_' . md5($asin);
    if (!$product = $this->cache->get($cacheKey)) {
        $product = $this->getProductDetails($asin);
        $this->cache->set($cacheKey, $product, '1 hour');
    }
    

Gotchas and Tips

Pitfalls

  1. AWS Rate Limits

    • The AWS Product Advertising API has strict rate limits. Exceeding limits (e.g., >1 request/second) will return AWSError with RequestThrottled.
    • Fix: Implement exponential backoff or use caching.
  2. XML Parsing Quirks

    • Some responses may return empty nodes (e.g., <RelatedItems></RelatedItems>). Always check for null or empty arrays when parsing:
      $relatedItems = $response->asArray()['Items']['Item']['RelatedItems'] ?? [];
      
  3. Missing Response Groups

    • If you request a ResponseGroup (e.g., Offers) but the product has no offers, the field will be missing. Validate expected fields:
      if (isset($response->asArray()['Items']['Item']['OfferSummary'])) {
          $price = $response->asArray()['Items']['Item']['OfferSummary']['LowestNewPrice']['Amount'];
      }
      
  4. ASIN vs. ISBN

    • ItemLookupRequest accepts both ASINs (10-digit) and ISBNs (13-digit). Ensure you’re using the correct format for your use case.
  5. Deprecated Methods

    • The bundle uses setASIN()/setISBN() for ItemLookupRequest, but newer AWS SDKs may prefer setIdType() and setIdValue(). Stick to the bundle’s methods unless extending.

Debugging Tips

  1. Enable Verbose Logging Configure Monolog to log AWS requests/responses:

    # config/packages/monolog.yaml
    handlers:
        aws:
            type: stream
            path: "%kernel.logs_dir%/aws.log"
            level: debug
            channels: ["aws"]
    

    Then enable AWS channel in your client:

    $this->client->setLogger($this->logger->pushHandler(new StreamHandler('php://stdout', Logger::DEBUG)));
    
  2. Raw Response Inspection Access the raw response for debugging:

    $rawResponse = $this->client->execute($request)->getRawResponse();
    file_put_contents('debug_aws_response.xml', $rawResponse);
    
  3. Validate Credentials Test credentials with a simple request:

    $testRequest = new ItemLookupRequest();
    $testRequest->setASIN('B00005JBY8'); // Known ASIN for "The AWS Bible"
    $this->client->execute($testRequest); // Should return data if credentials are valid
    

Extension Points

  1. Custom Request Types Extend Insig\AWSBundle\Request\AbstractRequest to add new API endpoints:

    class CustomRequest extends AbstractRequest {
        protected $endpoint = 'MyCustomEndpoint';
        protected $action = 'MyCustomAction';
    
        public function setCustomParam(string $value) {
            $this->setParam('CustomParam', $value);
        }
    }
    
  2. Response Transformers Create a custom response parser by implementing Insig\AWSBundle\Response\ResponseInterface:

    class CustomResponse implements ResponseInterface {
        public function asArray(): array {
            // Transform raw XML/response into your preferred structure
        }
    }
    
  3. Middleware for Requests Add preprocessing/POST-processing logic via events:

    // config/services.yaml
    services:
        App\EventListener\AWSPreRequestListener:
            tags:
                - { name: kernel.event_listener, event: insig.aws.pre_request, method: onPreRequest }
    
  4. Override Default Config Extend the bundle’s configuration in config/packages/insig_aws.yaml:

    insig_aws:
        client:
            access_key_id:     "%env(AWS_ACCESS_KEY_ID)%"
            secret_access_key: "%env(AWS_SECRET_ACCESS_KEY)%"
            associate_tag:     "your-associate-tag-20" # Optional: for tracking affiliate links
            region:            "us-east-1" # Override default region
    
  5. Mocking for Tests Use a mock client in tests:

    $mockClient = $this->createMock(Client::class);
    $mockClient->method('execute')
                ->willReturn(new Response(new SimpleXMLElement('<Items><Item><Title>Mock Title</Title></Item></Items>')));
    
    $this->container->set('insig_aws.client', $mockClient);
    
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin