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

Sendinblue Bridge Laravel Package

badpixxel/sendinblue-bridge

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require badpixxel/brevo-bridge
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        BadPixxel\BrevoBridge\BrevoBridgeBundle::class => ['all' => true],
    ];
    
  2. Configure Sendinblue API Key Add your Sendinblue API key to config/packages/brevo_bridge.yaml:

    brevo_bridge:
        api_key: '%env(BREVO_API_KEY)%'
        default_from: 'noreply@example.com'
    
  3. Define a Static Email Class Create a static class (e.g., src/Email/WelcomeEmail.php) extending BadPixxel\BrevoBridge\Email\AbstractEmail:

    namespace App\Email;
    
    use BadPixxel\BrevoBridge\Email\AbstractEmail;
    
    class WelcomeEmail extends AbstractEmail
    {
        protected static $name = 'Welcome Email';
        protected static $subject = 'Welcome to Our Platform!';
        protected static $templateId = 123; // Your Sendinblue template ID
        protected static $to = 'user@example.com';
        protected static $variables = [
            'username' => 'John Doe',
        ];
    }
    
  4. Send the Email Inject the BrevoBridgeService and dispatch:

    use BadPixxel\BrevoBridge\Service\BrevoBridgeService;
    
    class SomeController
    {
        public function __construct(private BrevoBridgeService $brevoService) {}
    
        public function sendWelcomeEmail()
        {
            $this->brevoService->send(WelcomeEmail::class);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Email Definition

    • Use static classes for reusable emails (e.g., PasswordResetEmail, InvoiceEmail).
    • Store template IDs, subjects, and variables in the class for maintainability.
    • Example for dynamic variables:
      protected static $variables = [
          'user' => fn() => ['name' => $user->name, 'id' => $user->id],
      ];
      
  2. Integration with Symfony Events Trigger emails via events (e.g., UserRegisteredEvent):

    // In an event subscriber
    $this->brevoService->send(WelcomeEmail::class, ['user' => $user]);
    
  3. Admin Panel Integration

    • Use Sonata Admin to track sent emails via SonataAdmin configuration:
      # config/packages/sonata_admin.yaml
      sonata_admin:
          options:
              models:
                  BadPixxel\BrevoBridge\Entity\EmailLog: ~
      
  4. Batch Processing

    • Queue emails for async sending (e.g., with Symfony Messenger):
      $this->brevoService->queue(WelcomeEmail::class, ['user' => $user]);
      

Advanced Patterns

  1. Dynamic Recipients Override getTo() in your email class to fetch recipients dynamically:

    protected function getTo(): array
    {
        return $this->userRepository->findAllActiveUsers();
    }
    
  2. Template Management

    • Use Sendinblue’s API to fetch/update templates programmatically:
      $this->brevoService->getTemplateManager()->fetchTemplate($templateId);
      
  3. Logging and Analytics

    • Extend EmailLog entity to add custom fields (e.g., campaign_id):
      // In a migration
      $table->integer('campaign_id')->nullable();
      
  4. Testing

    • Mock BrevoBridgeService in tests:
      $this->brevoService->shouldReceive('send')->once();
      

Gotchas and Tips

Pitfalls

  1. API Key Security

    • Never hardcode BREVO_API_KEY in config. Use environment variables or Symfony’s ParameterBag.
    • Restrict the key to transactional emails only in Sendinblue’s settings.
  2. Template IDs

    • Hardcoded template IDs (e.g., static::$templateId) can break if Sendinblue templates are renamed/deleted.
    • Fix: Fetch template IDs dynamically via the API or use a config-based approach:
      brevo_bridge:
          templates:
              welcome: 123
      
  3. Sonata Admin Dependencies

    • The bundle assumes sonata-project/user-bundle is installed. If not, disable the admin integration in config/packages/brevo_bridge.yaml:
      brevo_bridge:
          admin:
              enabled: false
      
  4. Rate Limits

    • Sendinblue’s API has rate limits. Handle 429 Too Many Requests gracefully:
      try {
          $this->brevoService->send(EmailClass::class);
      } catch (RateLimitExceededException $e) {
          $this->retryLater();
      }
      
  5. Database Schema

    • The email_log table is auto-created by Doctrine migrations. Customize the schema if needed:
      // src/Migrations/VersionYYYYMMDDHHMM.php
      $table->addColumn('status', 'string', ['length' => 20]);
      

Debugging Tips

  1. Enable API Logging Configure getbrevo/brevo-php to log requests:

    brevo_bridge:
        debug: true
    
  2. Check EmailLog Entries Query the email_log table for failed sends:

    SELECT * FROM email_log WHERE status = 'failed' ORDER BY created_at DESC;
    
  3. Validate Variables Ensure static::$variables are serializable. Non-serializable objects (e.g., closures with non-serializable context) will fail:

    // Bad: Closure with $this
    protected static $variables = ['data' => fn() => $this->fetchData()];
    
    // Good: Static or serializable data
    protected static $variables = ['data' => $serializedData];
    
  4. Test with Sandbox Mode Use Sendinblue’s sandbox API for testing:

    brevo_bridge:
        sandbox: true
    

Extension Points

  1. Custom Email Classes Extend AbstractEmail to add validation or pre-send logic:

    class CustomEmail extends AbstractEmail
    {
        public function validate(): bool
        {
            if (empty($this->getTo())) {
                throw new \RuntimeException('Recipient not set!');
            }
            return true;
        }
    }
    
  2. Event Listeners Dispatch custom events before/after sending:

    // In services.yaml
    BadPixxel\BrevoBridge\Event\EmailEvents::EMAIL_SENT:
        listeners:
            - [onEmailSent, App\EventListener\EmailListener]
    
  3. Transport Layer Replace the default Sendinblue client by overriding the service:

    # config/services.yaml
    BadPixxel\BrevoBridge\Service\BrevoBridgeService:
        arguments:
            $client: '@custom_brevo_client'
    
  4. Twig Integration Use Twig templates for dynamic content:

    protected static $templateId = null; // Disable Sendinblue template
    protected static $htmlTemplate = '@emails/welcome.html.twig';
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware