Send SMS from the Command Line


1Introduction

This short tutorial aims to create a CLI command that sends SMS messages to mobile phones.

To send SMS, we'll use the service smsmode.com, which provides an API. Temma offers a data source that lets you interact with this API transparently.

As a prerequisite, you’ll need to create an account on smsmode.com and generate an API key from the user interface.


2Project Setup

If you already have an existing Temma project, you can skip this step.

If your Temma project won’t serve a website and you won’t use Smarty templates, install it with the following command:

$ composer create-project digicreon/temma-project-api mon_api

If instead you want to create a full Temma project that can also serve a website, use:

$ composer create-project digicreon/temma-project-web mon_site

3Configuration

We'll stick to a minimal configuration with only the required essentials.

Edit the etc/temma.php file:

<?php

return [
    'application' => [
        'dataSources' => [
            'sms' => 'smsmode://API_KEY'
        ],
    ],
];
  • Line 6: This defines the data source connected to smsmode. Replace API_KEY with your actual smsmode API key.

4Controller

With Temma, CLI commands are written like web controllers, and executed using the comma program.

Here, we'll create a Sms controller with a send action.
Create the file cli/Sms.php:

<?php

/** Sms controller. */
class Sms extends \Temma\Web\Controller {
    /**
     * Action used to send SMS messages.
     * @param  string  $cellphone  Recipient’s phone number.
     * @param  string  $msg        Text message to send.
     */
    public function send(string $cellphone, string $msg) {
        // send the message
        $this->sms[$cellphone] = $msg;
    }
}

As you can see, the code is very simple.
The action takes two parameters: the recipient’s phone number, and the message to send.


5Execution

To run the controller, use Temma’s CLI tool comma, like any other command:

$ bin/comma Sms send --cellphone=336XXXXXXXX --msg="Hello World"

You can send the same message to multiple recipients by listing the phone numbers, separated by commas:

$ bin/comma Sms send --cellphone=336XXXXXXXX,336ZZZZZZZZ --msg="Hello"