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

Sms Bundle Laravel Package

creonit/sms-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require creonit/sms-bundle
    

    Enable the bundle in config/bundles.php:

    return [
        // ...
        Creonit\SmsBundle\CreonitSmsBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add credentials to config/packages/creonit_sms.yaml:

    creonit_sms:
        transport: Creonit\SmsBundle\Transport\SmsTrafficTransport
        transport_config:
            login: '%env(SMS_LOGIN)%'
            password: '%env(SMS_PASSWORD)%'
    

    Define env vars in .env:

    SMS_LOGIN=your_login
    SMS_PASSWORD=your_password
    
  3. First Use Case: Send a basic SMS via a controller:

    use Creonit\SmsBundle\Message\SmsMessage;
    use Creonit\SmsBundle\Mime\Phone;
    
    $message = new SmsMessage();
    $message
        ->setContent('Hello via SMS!')
        ->setTo(new Phone('1234567890'));
    
    $this->get('messenger.default_bus')->dispatch($message);
    

Implementation Patterns

Core Workflow

  1. Message Creation: Use SmsMessage to construct messages with:

    • setContent(): Message body (supports Unicode).
    • setTo()/addTo(): Recipients (accepts Phone objects or raw strings).
    • Optional: setFrom() for sender ID (if supported by provider).
  2. Dispatching:

    • Controller: Inject MessageBusInterface and dispatch directly.
    • Service: Create a dedicated SmsSender class (as shown in README) for reusable logic.
    • Command: Use Symfony’s Command component for CLI-based sends.
  3. Batch Processing: Loop through recipients and dispatch individually:

    foreach ($phoneNumbers as $number) {
        $message->addTo(new Phone($number));
    }
    $this->messageBus->dispatch($message);
    

Integration Tips

  • Validation: Validate phone numbers before dispatching (e.g., using libphonenumber).
  • Retry Logic: Configure Messenger middleware (e.g., RetryMiddleware) for failed sends.
  • Logging: Override SmsMessage to log sends/errors via Symfony’s logger.
  • Async: Use async transport in Messenger for background processing:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
    

Advanced Patterns

  1. Dynamic Content: Use Twig to render message content:

    $message->setContent($this->twig->render('sms_template.html.twig', ['user' => $user]));
    
  2. Provider Abstraction: Create a custom transport class to support multiple providers:

    class MultiProviderTransport implements TransportInterface {
        public function send(SmsMessage $message) {
            if ($this->isProviderA()) {
                $providerA->send($message);
            } else {
                $providerB->send($message);
            }
        }
    }
    
  3. Webhook Responses: Extend SmsMessage to handle delivery receipts via Messenger’s FailedMessage handling.


Gotchas and Tips

Pitfalls

  1. Phone Number Formatting:

    • Ensure numbers are in E.164 format (e.g., +1234567890). The bundle does not auto-format.
    • Test with Phone objects first to avoid silent failures.
  2. Transport Configuration:

    • The SmsTrafficTransport is hardcoded in the example. If switching providers, ensure the transport class exists and is properly configured.
    • No fallback: If the transport fails, the message is dropped unless Messenger retries are configured.
  3. Character Limits:

    • SMS messages are typically limited to 160 characters (70 for Unicode). Longer messages may be split or fail silently.
    • Check provider docs for exact limits.
  4. Synchronous Blocking:

    • Dispatching via dispatch() is synchronous by default. For long-running sends, use Messenger’s async transport.

Debugging

  1. Failed Messages: Enable Messenger’s failed_message transport to inspect failures:

    messenger:
        failure_transport: failed
    

    Check var/message/failed/ for details.

  2. Logging: Add debug logging to SmsMessage:

    use Psr\Log\LoggerInterface;
    
    class SmsMessage {
        public function __construct(private LoggerInterface $logger) {}
        public function dispatch() {
            $this->logger->debug('Sending SMS', ['content' => $this->content, 'to' => $this->to]);
        }
    }
    
  3. Provider-Specific Errors:

    • Wrap transport calls in try-catch to log provider-specific errors (e.g., SmsTrafficException).

Extension Points

  1. Custom Transports: Implement Creonit\SmsBundle\Transport\TransportInterface for new providers:

    class TwilioTransport implements TransportInterface {
        public function send(SmsMessage $message) {
            $client = new Client($this->config);
            $client->messages->create($message->to, [
                'body' => $message->content,
            ]);
        }
    }
    
  2. Message Events: Dispatch events for pre/post-send logic:

    use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
    
    class SmsMessage {
        public function __construct(private EventDispatcherInterface $dispatcher) {}
    
        public function dispatch() {
            $this->dispatcher->dispatch(new SmsSendEvent($this));
            // Send logic
        }
    }
    
  3. Validation: Override SmsMessage::validate() to add custom rules (e.g., blacklisted numbers):

    public function validate(): void {
        if (in_array($this->to, $this->blacklistedNumbers)) {
            throw new \InvalidArgumentException('Number blacklisted');
        }
    }
    

Configuration Quirks

  • Environment Variables: The bundle expects login/password in transport_config. Use %env() for security:

    transport_config:
        login: '%env(SMS_LOGIN)%'
        password: '%env(SMS_PASSWORD)%'
    
  • Default Transport: If transport is omitted, the bundle will not send messages. Always specify it.

  • Messenger Dependency: The bundle relies on Symfony Messenger. Ensure it’s installed and configured:

    composer require symfony/messenger
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager