This library allow us to send Laravel events to an SNS topic, and receive them through a SQS queue.
$ composer require ralbear/laravel-events-to-sns
Add the provider to config/app.php
'providers' => [
Ralbear\EventsToSns\EventsToSnsProvider::class
]
First step is create this new connection configuration in config/queue.php
'connections' => [
'sqs-sns' => [
'driver' => 'sqs-sns',
'key' => env('SQS_SNS_ACCESS_KEY_ID') ?? env('AWS_ACCESS_KEY_ID') ?? '',
'secret' => env('SQS_SNS_SECRET_ACCESS_KEY') ?? env('AWS_SECRET_ACCESS_KEY') ?? '',
'region' => env('SQS_SNS_DEFAULT_REGION') ?? env('AWS_DEFAULT_REGION') ?? '',
'base_ARN' => env('SQS_SNS_BASE_ARN') ?? '',
'valid_topics' => explode(',',env('SQS_SNS_VALID_TOPICS')) ?? [],
'prefix' => env('SQS_SNS_PREFIX') ?? env('SQS_PREFIX') ?? '',
'queue' => env('SQS_SNS_QUEUE') ?? env('SQS_QUEUE') ?? '',
'env_postfix' => env('SQS_SNS_ENV') ?? env('APP_ENV') ?? '',
'event_class_postfix' => 'Event'
],
]
If we use the same AWS account for SNS than for other AWS services on the application, we can use the default env keys for the credentials.
AWS_ACCESS_KEY_ID=<MAIN ACCESS KEY ID>
AWS_SECRET_ACCESS_KEY=<SECRECT ACCESS KEY>
AWS_DEFAULT_REGION=us-west-1
If we need specific credentials for SNS, use this env keys:
SQS_SNS_ACCESS_KEY_ID=<SNS ACCESS KEY ID>
SQS_SNS_SECRET_ACCESS_KEY=<SNS SECRET ACCESS KEY>
SQS_SNS_DEFAULT_REGION=eu-west-1
The way this library is designed, define SNS topics based on three parts.
- A: Use the env variable:
SQS_SNS_BASE_ARN=arn:aws:sns:eu-west-1:123456789
- B: Defined in your event:
public function getTopic()
{
return 'service-a-topic';
}
The event level topics we use, should be defined as a comma separated value on this env variable:
SQS_SNS_VALID_TOPICS=service-a-topic,service-b-topic
- D: Use the env variable if need a different value than
APP_ENV
:
SQS_SNS_ENV=local
This SQS_SNS_ENV
allow us to have custom topics for each environment, if we for example generate new environments for test specific features, we can set here the feature name.
<?php
namespace App\Events;
use App\Models\Order;
use Ralbear\EventsToSns\Contracts\ShouldBeInSns;
use Ralbear\EventsToSns\Traits\SendToSns;
class OrderCreatedEvent implements ShouldBeInSns
{
use SendToSns;
public $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function uniqueId()
{
return $this->order->id;
}
public function getTopic()
{
return 'service-a-topic';
}
}
Run the worker:
$ php artisan queue:worker sqs-sns
<?php
namespace App\Jobs;
use Illuminate\Queue\Jobs\SqsJob;
class OrderCreatedJob
{
public function handle(SqsJob $job, $data)
{
//Do something nice with your $data
$job->delete();
}
}
To run test:
$ composer test
- Improve tests and coverage
Laravel events to SNS is open-sourced software licensed under the MIT license.