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

Brevo Bridge Laravel Package

badpixxel/brevo-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 Brevo API Key Add your Brevo (Sendinblue) API key to .env:

    BREVO_API_KEY=your_api_key_here
    

    Publish the default config (if needed):

    php bin/console config:dump-reference BadPixxel\BrevoBridgeBundle
    
  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 $templateId = 'your_brevo_template_id';
        protected static $subject = 'Welcome to Our App!';
    }
    
  4. Send Your First Email Inject the BrevoBridge service and trigger the email:

    use BadPixxel\BrevoBridge\BrevoBridge;
    
    class UserController
    {
        public function __construct(private BrevoBridge $brevoBridge) {}
    
        public function registerUser()
        {
            $email = new WelcomeEmail();
            $this->brevoBridge->send($email, 'user@example.com');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Email Definition & Reusability

    • Store all email templates as static classes in src/Email/ (e.g., PasswordResetEmail, InvoiceEmail).
    • Extend AbstractEmail to define:
      • $templateId (Brevo template ID).
      • $subject (fallback subject if template lacks one).
      • Optional: $fromEmail, $replyTo, or custom logic in getData().
    • Example:
      class InvoiceEmail extends AbstractEmail
      {
          protected static $templateId = 'invoice_template_123';
          protected static $subject = 'Your Invoice #{{invoiceId}}';
      
          public function getData($invoice): array
          {
              return [
                  'invoiceId' => $invoice->id,
                  'amount' => $invoice->amount,
                  'dueDate' => $invoice->dueDate->format('Y-m-d'),
              ];
          }
      }
      
  2. Integration with Symfony Services

    • Event Listeners: Trigger emails post-actions (e.g., user registration, order confirmation).
      use BadPixxel\BrevoBridge\BrevoBridge;
      use Symfony\Component\HttpKernel\Event\RequestEvent;
      
      class EmailListener
      {
          public function __construct(private BrevoBridge $brevoBridge) {}
      
          public function onKernelRequest(RequestEvent $event)
          {
              if ($event->isMainRequest() && $event->getRequest()->isXmlHttpRequest()) {
                  return;
              }
              // Logic to trigger emails...
          }
      }
      
    • Commands: Batch-send emails (e.g., newsletters).
      use BadPixxel\BrevoBridge\BrevoBridge;
      use Symfony\Component\Console\Command\Command;
      use Symfony\Component\Console\Input\InputInterface;
      use Symfony\Component\Console\Output\OutputInterface;
      
      class SendNewsletterCommand extends Command
      {
          protected static $defaultName = 'app:send-newsletter';
      
          public function __construct(private BrevoBridge $brevoBridge) {}
      
          protected function execute(InputInterface $input, OutputInterface $output): int
          {
              $newsletter = new NewsletterEmail();
              $subscribers = $this->getSubscribers(); // Fetch from DB
              foreach ($subscribers as $subscriber) {
                  $this->brevoBridge->send($newsletter, $subscriber->email, [
                      'user' => $subscriber->name,
                  ]);
              }
              return Command::SUCCESS;
          }
      }
      
  3. Dynamic Data Injection

    • Override getData() in your email class to inject dynamic values:
      public function getData($user): array
      {
          return [
              'firstName' => $user->firstName,
              'verificationLink' => route('verify_email', ['token' => $user->verificationToken]),
          ];
      }
      
    • Pass data at runtime:
      $this->brevoBridge->send($email, 'user@example.com', ['customKey' => 'value']);
      
  4. Sonata Admin Integration

    • Log sent emails in the admin panel:
      • Ensure SonataAdminBundle and DoctrineORMAdminBundle are installed.
      • The bundle auto-registers BrevoEmail entities in Sonata Admin (check config/packages/sonata_admin.yaml for overrides).
    • Customize the admin view by extending the provided CRUD controller.

Advanced Patterns

  1. Queueing Emails

    • Use Symfony Messenger to defer email sending:
      use BadPixxel\BrevoBridge\Message\SendEmailMessage;
      
      $this->messageBus->dispatch(
          new SendEmailMessage($email, 'user@example.com', $data)
      );
      
    • Configure the transport in config/packages/messenger.yaml:
      framework:
          messenger:
              transports:
                  async: '%env(MESSENGER_TRANSPORT_DSN)%'
              routing:
                  'BadPixxel\BrevoBridge\Message\SendEmailMessage': async
      
  2. Template Versioning

    • Maintain a templates table to track active Brevo template IDs per email type.
    • Fetch the latest template ID dynamically:
      class WelcomeEmail extends AbstractEmail
      {
          protected static function getTemplateId(): string
          {
              return $this->templateRepository->findActiveTemplate('welcome');
          }
      }
      
  3. Fallback Logic

    • Implement a fallback to Symfony Mailer if Brevo fails:
      use Symfony\Component\Mailer\MailerInterface;
      
      class BrevoBridge extends AbstractBrevoBridge
      {
          public function __construct(
              private MailerInterface $mailer,
              // ...
          ) {}
      
          public function send(AbstractEmail $email, string $to, array $data = []): void
          {
              try {
                  parent::send($email, $to, $data);
              } catch (BrevoException $e) {
                  $this->fallbackToSymfonyMailer($email, $to, $data);
              }
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Version

    • The bundle supports Symfony 5.4–8.0 but was last updated in 2020. Test thoroughly with your Symfony version.
    • Fix: Override deprecated method calls or use a compatibility layer (e.g., symfony/polyfill).
  2. Brevo API Rate Limits

    • Brevo enforces rate limits. Handle BrevoException for 429 Too Many Requests:
      try {
          $this->brevoBridge->send($email, $to);
      } catch (BrevoException $e) {
          if ($e->getCode() === 429) {
              sleep($e->getRetryAfter()); // Respect Retry-After header
              retry();
          }
          throw $e;
      }
      
  3. Sonata Admin Conflicts

    • If emails don’t appear in Sonata Admin:
      • Ensure sonata_project_user is installed and configured.
      • Clear cache:
        php bin/console cache:clear
        php bin/console sonata:admin:rebuild
        
  4. Static Class Limitations

    • Static email classes cannot access non-static dependencies (e.g., services, repositories).
    • Workaround: Pass dependencies via constructor in getData():
      public function getData(UserRepository $userRepo, $userId): array
      {
          $user = $userRepo->find($userId);
          return ['name' => $user->name];
      }
      
      Then inject the repo when sending:
      $this->brevoBridge->send($email, $to, [], [$userRepo]);
      
  5. Template ID Mismatches

    • Hardcoded $templateId in email classes may break if Brevo template IDs change.
    • Tip: Fetch IDs dynamically from a config file or database.

Debugging Tips

  1. Enable API Debugging
    • Log raw Brevo API responses:
      # config/packages/monolog.yaml
      handlers:
          brevo:
              type: stream
              path: "%kernel.logs_dir%/%kernel.environment%.brevo.log"
              level: debug
              channels: ["bre
      
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