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

Sns Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require async-aws/sns
    
  2. Configure AWS credentials in .env:
    AWS_ACCESS_KEY_ID=your_key
    AWS_SECRET_ACCESS_KEY=your_secret
    AWS_DEFAULT_REGION=us-east-1
    
  3. Basic publish example (in a Laravel controller or command):
    use AsyncAws\Sns\SnsClient;
    
    $sns = app(SnsClient::class);
    $result = $sns->publish([
        'TopicArn' => 'arn:aws:sns:us-east-1:123456789012:my-topic',
        'Message' => 'Hello, SNS!',
    ]);
    

First Use Case: Publishing a Notification

// 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]),
        ],
    ]);
}

Key Starting Points

  • Official Documentation (API reference, input/output objects).
  • Laravel Service Provider: Bind the client in AppServiceProvider for dependency injection.
  • Input/Output Classes: Explore AsyncAws\Sns\Input\* and AsyncAws\Sns\Output\* for type safety.

Implementation Patterns

Core Workflows

1. Pub/Sub Pattern

// 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/...',
]);

2. Event-Driven Laravel Integration

// 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...
}

3. Batch Publishing

$sns->publishBatch([
    'PublishRequests' => [
        ['TopicArn' => 'arn:...', 'Message' => 'Batch message 1'],
        ['TopicArn' => 'arn:...', 'Message' => 'Batch message 2'],
    ],
]);

4. Topic Management

// Create a topic
$topic = $sns->createTopic(['Name' => 'my-topic']);
$topicArn = $topic->getTopicArn();

// Delete a topic
$sns->deleteTopic(['TopicArn' => $topicArn]);

Laravel-Specific Patterns

Dependency Injection

// In a Laravel controller
public function __construct(private SnsClient $sns) {}

public function notify()
{
    $this->sns->publish([...]);
}

Configuration

// config/services.php
'sns' => [
    'topic_arn' => env('SNS_TOPIC_ARN'),
    'default_region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],

Exception Handling

try {
    $sns->publish([...]);
} catch (SnsException $e) {
    Log::error('SNS publish failed', ['error' => $e->getAwsErrorCode()]);
    // Retry or notify monitoring
}

Testing with Mocks

// Use VCR or Mockery to stub SNS responses
$mock = Mockery::mock(SnsClient::class);
$mock->shouldReceive('publish')
     ->once()
     ->withArgs([...]);

Gotchas and Tips

Pitfalls

1. Region Configuration

  • Gotcha: Forgetting to set the correct AWS region can lead to silent failures or InvalidParameter errors.
  • Fix: Explicitly pass the region in the client constructor or set it via .env:
    $sns = new SnsClient(['region' => 'eu-west-1']);
    

2. Message Size Limits

  • Gotcha: SNS has a 256KB payload limit. Large messages (e.g., JSON-encoded objects) may fail.
  • Fix: Use S3 + SNS for large payloads or compress data.

3. FIFO Topic Quirks

  • Gotcha: FIFO topics require deduplication IDs and message groups. Omitting these causes InvalidParameter errors.
  • Fix:
    $sns->publish([
        'TopicArn' => 'fifo-topic.fifo',
        'Message' => '...',
        'MessageDeduplicationId' => uniqid(),
        'MessageGroupId' => 'group1',
    ]);
    

4. Subscription Confirmations

  • Gotcha: HTTP/HTTPS subscriptions require manual confirmation via the returned SubscribeUrl.
  • Fix: Automate confirmation in a Laravel command:
    $response = $sns->subscribe([...]);
    file_get_contents($response->getSubscribeUrl());
    

5. Permissions

  • Gotcha: Missing IAM permissions (e.g., sns:Publish) result in AccessDenied errors.
  • Fix: Attach the 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"]
      }]
    }
    

Debugging Tips

1. Enable Debug Logging

$sns = new SnsClient([
    'region' => 'us-east-1',
    'debug' => true, // Enable debug logs
]);

Logs will show raw AWS API requests/responses.

2. Validate Inputs

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

3. Handle Throttling

Implement exponential backoff for 429 TooManyRequests:

use AsyncAws\Core\Exception\ThrottlingException;

try {
    $sns->publish([...]);
} catch (ThrottlingException $e) {
    sleep(2 ** $e->getRetryAfter());
    retry();
}

Extension Points

1. Custom Middleware

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;
            }
        },
    ],
]);

2. Laravel Facade

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([...]);

3. Event Listeners for SNS

Trigger Laravel events when SNS messages arrive (e.g., via SQS):

// Listen for SnsMessageReceived events
Event::listen(SnsMessageReceived::class, function ($event) {
    // Process the message
});

4. Dynamic Topic ARNs

Use Laravel’s config() or env() to manage topic ARNs dynamically:

$topicArn
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity