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

Cm Sms Bundle Laravel Package

bassim/cm-sms-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require bassim/cm-sms-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Bassim\CmSmsBundle\BassimCmSmsBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console config:dump-reference Bassim\CmSmsBundle\Resources\config\services.yml > config/packages/cm_sms.yaml
    

    Update config/packages/cm_sms.yaml with your CM Telecom credentials:

    cm_sms:
        username: 'your_username'
        password: 'your_password'
        sender_id: 'your_sender_id'
    
  3. First Use Case Inject the SMS service into a controller or command:

    use Bassim\CmSmsBundle\Service\SmsService;
    
    class SendSmsController extends AbstractController
    {
        public function send(SmsService $smsService)
        {
            $response = $smsService->send(
                '+212612345678', // Recipient
                'Hello from Laravel!' // Message
            );
    
            return new Response($response);
        }
    }
    

Implementation Patterns

Core Workflow

  1. Service Injection Use dependency injection to access SmsService in controllers, commands, or services:

    public function __construct(private SmsService $smsService) {}
    
  2. Sending SMS Basic usage:

    $smsService->send('+212612345678', 'Your message');
    

    For bulk sends (if supported):

    $smsService->sendBulk(['+212612345678', '+212698765432'], 'Broadcast message');
    
  3. Error Handling Wrap calls in try-catch:

    try {
        $response = $smsService->send($phone, $message);
    } catch (\Exception $e) {
        // Log or handle CM Telecom API errors (e.g., invalid credentials, rate limits)
        $this->addFlash('error', 'Failed to send SMS: ' . $e->getMessage());
    }
    
  4. Integration with Laravel Queues (Advanced) Dispatch a job for async sending:

    use Bassim\CmSmsBundle\Jobs\SendSmsJob;
    
    SendSmsJob::dispatch($phone, $message)->onQueue('sms');
    

    (Note: Requires custom job class or queue listener setup.)


Common Patterns

  • Logging Responses Log raw responses for debugging:

    $response = $smsService->send($phone, $message);
    \Log::debug('CM SMS Response', ['data' => $response]);
    
  • Configuration Overrides Override config per environment (e.g., config/packages/cm_sms_test.yaml):

    cm_sms:
        username: '%env(CM_SMS_TEST_USERNAME)%'
        sender_id: 'TEST_SENDER'
    
  • Testing Mock the service in PHPUnit:

    $mock = $this->createMock(SmsService::class);
    $mock->method('send')->willReturn(['status' => 'success']);
    $this->container->set(SmsService::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony2 Bundle

    • The bundle targets Symfony 2.x (last updated 2015). Ensure compatibility with Symfony 3/4/5/6 by:
      • Checking for breaking changes in ServiceProvider or DependencyInjection extensions.
      • Overriding services if autowiring fails:
        # config/services.yaml
        Bassim\CmSmsBundle\Service\SmsService: ~
        
  2. No Modern Laravel Support

    • No Eloquent models, no queue jobs, or no event system integration. Build wrappers if needed:
      // Example: Event listener for model events
      class UserSmsListener
      {
          public function __construct(private SmsService $smsService) {}
      
          public function handle(UserRegistered $event)
          {
              $this->smsService->send($event->user->phone, 'Welcome!');
          }
      }
      
  3. Hardcoded Dependencies

    • The bundle assumes CM Telecom’s specific API format. If their API changes:
      • Extend the SmsService class:
        class CustomSmsService extends SmsService
        {
            protected function buildRequest($phone, $message)
            {
                // Override to adapt to new API
                return [
                    'to' => $phone,
                    'text' => $message,
                    'new_param' => 'value',
                ];
            }
        }
        
      • Register the override in config/services.yaml:
        services:
            Bassim\CmSmsBundle\Service\SmsService: '@custom_sms_service'
        
  4. No Rate Limiting

    • The bundle lacks built-in rate limiting. Implement middleware or a decorator:
      class RateLimitedSmsService
      {
          public function __construct(private SmsService $smsService) {}
      
          public function send($phone, $message)
          {
              if ($this->isRateLimited($phone)) {
                  throw new \RuntimeException('Rate limit exceeded');
              }
              return $this->smsService->send($phone, $message);
          }
      }
      
  5. Security Risks

    • Hardcoded credentials in config/packages/cm_sms.yaml are exposed. Use environment variables:
      cm_sms:
          username: '%env(CM_SMS_USERNAME)%'
          password: '%env(CM_SMS_PASSWORD)%'
      

Debugging Tips

  1. Enable Verbose Logging Add to config/packages/monolog.yaml:

    handlers:
        main:
            type: stream
            path: '%kernel.logs_dir%/%kernel.environment%.log'
            level: debug
            channels: ['!event']
    
  2. Inspect Raw Requests Decorate SmsService to log requests:

    class DebugSmsService implements SmsServiceInterface
    {
        public function __construct(private SmsService $smsService) {}
    
        public function send($phone, $message)
        {
            \Log::debug('SMS Request', [
                'phone' => $phone,
                'message' => $message,
                'timestamp' => now()->toIso8601String(),
            ]);
            return $this->smsService->send($phone, $message);
        }
    }
    
  3. Test with CM Telecom’s Sandbox Use a test sender ID (e.g., TEST123) and verify messages arrive in the CM Telecom sandbox environment.


Extension Points

  1. Custom Response Handling Extend the bundle to parse CM Telecom’s API responses:

    class CustomSmsService extends SmsService
    {
        protected function parseResponse($rawResponse)
        {
            if (isset($rawResponse['error'])) {
                throw new \RuntimeException($rawResponse['error']['message']);
            }
            return $rawResponse['success'] ?? false;
        }
    }
    
  2. Add Twilio/Vonage Fallback Implement a fallback service:

    class MultiProviderSmsService
    {
        public function __construct(
            private SmsService $cmSmsService,
            private TwilioService $twilioService
        ) {}
    
        public function send($phone, $message)
        {
            try {
                return $this->cmSmsService->send($phone, $message);
            } catch (\Exception $e) {
                return $this->twilioService->send($phone, $message);
            }
        }
    }
    
  3. Laravel Notifications Channel Create a custom notification channel:

    use Illuminate\Notifications\Notification;
    
    class SendSmsViaCmTelecom implements ShouldQueue
    {
        public function via($notifiable)
        {
            return [new CmSmsChannel()];
        }
    
        public function toCmSms($notifiable, Notification $notification)
        {
            return $notification->toSms($notifiable);
        }
    }
    
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.
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
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle