async-aws/sns
AsyncAws SNS client for PHP: publish messages, send SMS, manage topics and subscriptions, and integrate with AWS SNS without the full AWS SDK. Lightweight, async-friendly, PSR-18/PSR-7 compatible for modern apps and Laravel.
composer require async-aws/sns
.env:
AWS_ACCESS_KEY_ID=your_key
AWS_SECRET_ACCESS_KEY=your_secret
AWS_DEFAULT_REGION=us-east-1
use AsyncAws\Sns\SnsClient;
$sns = app(SnsClient::class);
$result = $sns->publish([
'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:my-topic',
'Message' => 'Hello, SNS!',
]);
// In a Laravel Notification channel or service
public function send(SnsMessage $message)
{
$sns = app(SnsClient::class);
$sns->publish([
'TopicArn' => config('services.sns.topic_arn'),
'Message' => json_encode($message->toArray()),
'MessageAttributes' => [
new MessageAttributeValue(['DataType' => 'String', 'StringValue' => $message->type]),
],
]);
}
AppServiceProvider for dependency injection.AsyncAws\Sns\Input\* and AsyncAws\Sns\Output\* for type safety.// Publish to a topic
$sns->publish([
'TopicArn' => 'arn:...',
'Message' => 'Order created',
'MessageStructure' => 'json', // For structured messages
]);
// Subscribe to a topic (e.g., SQS, HTTP, Lambda)
$sns->subscribe([
'TopicArn' => 'arn:...',
'Protocol' => 'sqs',
'Endpoint' => 'https://sqs.us-east-1.amazonaws.com/...',
]);
// Dispatch Laravel event to SNS
Event::listen(UserRegistered::class, function ($event) {
$sns = app(SnsClient::class);
$sns->publish([
'TopicArn' => config('services.sns.user_events'),
'Message' => json_encode(['event' => 'user.registered', 'data' => $event->toArray()]),
]);
});
// Handle SNS messages in a Laravel job
public function handle(SnsMessage $message)
{
$payload = json_decode($message->getMessage(), true);
// Process payload...
}
$sns->publishBatch([
'PublishRequests' => [
['TopicArn' => 'arn:...', 'Message' => 'Batch message 1'],
['TopicArn' => 'arn:...', 'Message' => 'Batch message 2'],
],
]);
// Create a topic
$topic = $sns->createTopic(['Name' => 'my-topic']);
$topicArn = $topic->getTopicArn();
// Delete a topic
$sns->deleteTopic(['TopicArn' => $topicArn]);
// In a Laravel controller
public function __construct(private SnsClient $sns) {}
public function notify()
{
$this->sns->publish([...]);
}
// config/services.php
'sns' => [
'topic_arn' => env('SNS_TOPIC_ARN'),
'default_region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
try {
$sns->publish([...]);
} catch (SnsException $e) {
Log::error('SNS publish failed', ['error' => $e->getAwsErrorCode()]);
// Retry or notify monitoring
}
// Use VCR or Mockery to stub SNS responses
$mock = Mockery::mock(SnsClient::class);
$mock->shouldReceive('publish')
->once()
->withArgs([...]);
InvalidParameter errors..env:
$sns = new SnsClient(['region' => 'eu-west-1']);
InvalidParameter errors.$sns->publish([
'TopicArn' => 'fifo-topic.fifo',
'Message' => '...',
'MessageDeduplicationId' => uniqid(),
'MessageGroupId' => 'group1',
]);
SubscribeUrl.$response = $sns->subscribe([...]);
file_get_contents($response->getSubscribeUrl());
sns:Publish) result in AccessDenied errors.AmazonSNSFullAccess policy or use least-privilege roles:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["sns:Publish"],
"Resource": ["arn:aws:sns:us-east-1:123456789012:my-topic"]
}]
}
$sns = new SnsClient([
'region' => 'us-east-1',
'debug' => true, // Enable debug logs
]);
Logs will show raw AWS API requests/responses.
Use the package’s input classes for validation:
use AsyncAws\Sns\Input\PublishInput;
$input = new PublishInput([
'TopicArn' => 'arn:...',
'Message' => 'Hello',
]);
$sns->publish($input); // Throws validation errors if invalid
Implement exponential backoff for 429 TooManyRequests:
use AsyncAws\Core\Exception\ThrottlingException;
try {
$sns->publish([...]);
} catch (ThrottlingException $e) {
sleep(2 ** $e->getRetryAfter());
retry();
}
Add request/response middleware for logging, metrics, or transformations:
$sns = new SnsClient([
'middleware' => [
new class implements Middleware {
public function handle(Request $request, callable $next) {
// Pre-process request
$response = $next($request);
// Post-process response
return $response;
}
},
],
]);
Create a facade for cleaner syntax:
// app/Facades/Sns.php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class Sns extends Facade {
protected static function getFacadeAccessor() {
return 'sns';
}
}
Bind the client in AppServiceProvider:
$this->app->singleton('sns', function () {
return new SnsClient(['region' => config('services.sns.region')]);
});
Usage:
Sns::publish([...]);
Trigger Laravel events when SNS messages arrive (e.g., via SQS):
// Listen for SnsMessageReceived events
Event::listen(SnsMessageReceived::class, function ($event) {
// Process the message
});
Use Laravel’s config() or env() to manage topic ARNs dynamically:
$topicArn
How can I help you explore Laravel packages today?