Install the Bundle
composer require damonjones/insig-aws-bundle
Register the bundle in config/bundles.php:
return [
// ...
DamonJones\InsigAWSBundle\InsigAWSBundle::class => ['all' => true],
];
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)%"
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'];
}
}
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);
Response Handling Responses can be parsed as:
$response->asXml()$response->asArray()$response->asSimpleXml()Example with XML:
$xml = $response->asXml();
$title = $xml->Items->Item->ItemAttributes->Title;
Dependency Injection
Prefer injecting the Insig\AWSBundle\Client interface into services:
public function __construct(
private readonly Client $awsClient,
private readonly LoggerInterface $logger
) {}
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);
}
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');
}
AWS Rate Limits
AWSError with RequestThrottled.XML Parsing Quirks
<RelatedItems></RelatedItems>). Always check for null or empty arrays when parsing:
$relatedItems = $response->asArray()['Items']['Item']['RelatedItems'] ?? [];
Missing Response Groups
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'];
}
ASIN vs. ISBN
ItemLookupRequest accepts both ASINs (10-digit) and ISBNs (13-digit). Ensure you’re using the correct format for your use case.Deprecated Methods
setASIN()/setISBN() for ItemLookupRequest, but newer AWS SDKs may prefer setIdType() and setIdValue(). Stick to the bundle’s methods unless extending.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)));
Raw Response Inspection Access the raw response for debugging:
$rawResponse = $this->client->execute($request)->getRawResponse();
file_put_contents('debug_aws_response.xml', $rawResponse);
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
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);
}
}
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
}
}
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 }
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
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);
How can I help you explore Laravel packages today?