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

Symfony Sms Bundle Laravel Package

cspoo/symfony-sms-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cspoo/symfony-sms-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 2/3):

    return [
        // ...
        cspoo\SmsBundle\cspooSmsBundle::class => ['all' => true],
    ];
    
  2. Configure the Bundle Add a config/packages/cspoo_sms.yaml (Symfony 4+) or app/config/config.yml (Symfony 2/3):

    cspoo_sms:
        default_transport: twilio  # or your provider name
        transports:
            - { name: twilio, type: twilio, account_sid: '...', auth_token: '...' }
    
  3. First Use Case Send an SMS in a controller:

    use Symfony\Component\HttpFoundation\Request;
    
    public function sendSmsAction(Request $request)
    {
        $smsSender = $this->get('sms');
        $sms = $smsSender->createSms('+1234567890', 'Your verification code is 12345');
        $smsSender->sendSms($sms);
    
        return new Response('SMS sent!');
    }
    

Implementation Patterns

Common Workflows

  1. Sending SMS

    $smsSender = $this->get('sms');
    $sms = $smsSender->createSms($phoneNumber, $message);
    $result = $smsSender->sendSms($sms); // Returns provider-specific response (e.g., message ID)
    
  2. Using Different Transports

    # config/packages/cspoo_sms.yaml
    cspoo_sms:
        transports:
            - { name: twilio, type: twilio, ... }
            - { name: nexmo, type: nexmo, ... }
    
    // Send via Nexmo
    $smsSender->setTransport('nexmo');
    $smsSender->sendSms($sms);
    
  3. Dependency Injection Inject the SmsSender service directly into services/controllers:

    use cspoo\SmsBundle\Sms\SmsSender;
    
    public function __construct(SmsSender $smsSender) {
        $this->smsSender = $smsSender;
    }
    
  4. Batch Sending Loop through recipients and send SMS in bulk (handle rate limits):

    foreach ($recipients as $phone) {
        $sms = $this->smsSender->createSms($phone, $message);
        $this->smsSender->sendSms($sms);
        // Add delay if needed (e.g., sleep(1))
    }
    
  5. Logging and Error Handling Wrap SMS sending in a try-catch block and log failures:

    try {
        $this->smsSender->sendSms($sms);
    } catch (\Exception $e) {
        $this->logger->error('SMS failed: ' . $e->getMessage());
        // Retry logic or fallback (e.g., email)
    }
    

Integration Tips

  1. Laravel-Specific Setup

    • For Laravel (Symfony-based), use config/services.php to bind the service:
      'sms' => \cspoo\SmsBundle\Sms\SmsSender::class,
      
    • Access via the container:
      $smsSender = app('sms');
      
  2. Environment Variables Store sensitive credentials (e.g., username, password) in .env:

    SMS_WINIC_USERNAME=foo
    SMS_WINIC_PASSWORD=bar
    

    Reference them in config:

    transports:
        - { name: winic, type: winic, username: '%env(SMS_WINIC_USERNAME)%' }
    
  3. Event Listeners Trigger actions post-SMS (e.g., update user record):

    $this->eventDispatcher->dispatch(new SmsSentEvent($sms));
    
  4. Testing Mock the SmsSender in PHPUnit:

    $mockSmsSender = $this->createMock(SmsSender::class);
    $mockSmsSender->expects($this->once())->method('sendSms')->with($sms);
    $this->app->instance('sms', $mockSmsSender);
    

Gotchas and Tips

Pitfalls

  1. Transport Class Naming

    • The example uses WinicTransport, but the config key is type: winic. Ensure the class name matches the type in config (e.g., TwilioTransport for type: twilio).
  2. BaseTransport Inheritance

    • Extend BaseTransport (not Transport) to avoid missing methods like getUsername() or getPassword():
      class MyTransport extends \cspoo\SmsBundle\Transport\BaseTransport { ... }
      
  3. Configuration Overrides

    • If using Symfony Flex or auto-config, ensure the bundle’s config is loaded after your overrides. Use imports in config/packages/cspoo_sms.yaml:
      imports:
          - { resource: cspoo_sms.yaml }
      
  4. Deprecated Methods

    • Avoid createSms() with raw strings. Use the Sms model for structured data (e.g., recipients, parts):
      $sms = new \cspoo\SmsBundle\Model\Sms();
      $sms->setRecipient($phone)->setMessage($message);
      
  5. Rate Limiting

    • Providers like Twilio or Nexmo throttle requests. Implement exponential backoff or queue the jobs (e.g., Laravel Queues):
      dispatch(new SendSmsJob($phone, $message))->delay(now()->addSeconds(5));
      

Debugging Tips

  1. Enable Debug Mode Set debug: true in config to log transport interactions:

    cspoo_sms:
        debug: true
    
  2. Check Transport Responses Log the return value of sendSms() to verify provider-specific responses:

    $response = $smsSender->sendSms($sms);
    $this->logger->debug('SMS response:', ['response' => $response]);
    
  3. Validate Phone Numbers Use a library like libphonenumber to format numbers before sending:

    use giggsey\LibPhonenumber\PhoneNumberUtil;
    $phoneUtil = PhoneNumberUtil::getInstance();
    $phone = $phoneUtil->parse($rawPhone, 'US');
    $sms->setRecipient($phoneUtil->format($phone, PhoneNumberFormat::E164));
    

Extension Points

  1. Custom Transport Logic Override sendSms() in your transport class to add features like:

    • Message scheduling:
      public function sendSms(Sms $sms) {
          $this->scheduleMessage($sms->getMessage(), $sms->getRecipient(), $sms->getSentAt());
          return 'scheduled';
      }
      
    • Unicode support:
      $content = urlencode(mb_convert_encoding($sms->getMessage(), 'UTF-8'));
      
  2. Add Metadata to SMS Extend the Sms model to include custom fields (e.g., template_id, campaign_id):

    class ExtendedSms extends \cspoo\SmsBundle\Model\Sms {
        private $templateId;
    
        public function setTemplateId($id) { $this->templateId = $id; }
        public function getTemplateId() { return $this->templateId; }
    }
    
  3. Hook into the Factory Modify SmsFactory.php to add pre-send validation or logging:

    public function sendSms(Sms $sms) {
        $this->logger->info('Sending SMS to ' . $sms->getRecipient());
        return $this->getTransport()->sendSms($sms);
    }
    
  4. Support for Multi-Part SMS Extend the bundle to handle long messages by splitting them into parts:

    public function sendSms(Sms $sms) {
        $parts = $this->splitMessage($sms->getMessage());
        foreach ($parts as $part) {
            $this->sendPart($part, $sms->getRecipient());
        }
    }
    

Laravel-Specific Quirks

  1. Service Provider Binding In Laravel, bind the bundle’s services in AppServiceProvider
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui