Machine

The Machine class is the central orchestrator that manages the entire USSD application flow. It handles state resolution, user input processing, session continuity, and state transitions throughout the session lifecycle.

Understanding the Machine

The Machine class acts as the application runner, managing the flow of the USSD application. It interprets user requests, navigates between states, and handles session management. The Machine ensures seamless interaction between the user and the application by coordinating all the moving parts.

How the Machine Works

The Machine orchestrates the entire USSD session flow through the following process:

  1. Load Session: Loads existing session context or creates a new one
  2. Check Continuity: Determines if session resume should be offered
  3. Resolve State: Instantiates the current state class using Laravel's container
  4. Process Input: Handles user input and determines the next state
  5. Transition: Moves to the next state or ends the session

The handle() Method

The primary method of the Machine class is handle(), which processes incoming USSD requests:

public function handle(array $payload): UssdResponse
{
    // Payload contains:
    // - sessionId: Unique session identifier
    // - msisdn: Phone number of the user
    // - input: User's input (empty string for initial request)
    
    // Load or create session context
    $context = $this->sessions->load($payload['sessionId'], $payload['msisdn']);
    
    // Check for session resume
    if ($this->shouldOfferResume($context) && empty($payload['input'])) {
        return $this->makeResumePrompt($context);
    }
    
    // Resolve and process current state
    $state = $this->resolveState($context->currentState);
    
    // Handle state entry or input processing
    // ...
}

Session Lifecycle Management

The Machine manages the complete session lifecycle:

Session Initialization

When a new session starts, the Machine creates a new context with the configured initial state from config/ussd.php.

State Transitions

The Machine handles transitions between states by calling the next() method on the current state, which returns the next state class name.

Session Persistence

After each state transition, the Machine saves the session context to storage, ensuring data persistence across requests.

Session Termination

When a state returns null as the next state, the Machine clears the session data and ends the USSD session.

Session Continuity

The Machine supports session continuity, allowing users to resume interrupted sessions:

// Machine checks if session resume should be offered
if ($this->shouldOfferResume($context) && empty($payload['input'])) {
    return $this->makeResumePrompt($context);
}

// User can choose to:
// 1. Resume previous session (continues from last state)
// 2. Start over (begins from initial state)

Session continuity is controlled by the continuity configuration in config/ussd.php.

State Resolution

The Machine uses Laravel's service container to resolve state classes, which means:

  • States can use dependency injection
  • States are automatically instantiated with their dependencies
  • You can bind custom implementations in service providers
protected function resolveState(string $class): State
{
    return $this->container->make($class);
}

Events

The Machine dispatches events throughout the session lifecycle, allowing you to hook into the flow:

StateEntered

Dispatched when a user enters a state. Provides access to the context and state class name.

StateExited

Dispatched when a user exits a state (after processing input).

SessionResumed

Dispatched when a user chooses to resume a previous session.

SessionRestarted

Dispatched when a user chooses to start over from the beginning.

Usage in Controllers

The Machine is typically used in the USSD controller to handle incoming requests:

<?php

namespace Vendor\LaravelUssd\Http\Controllers;

use Illuminate\Http\Request;
use Vendor\LaravelUssd\Machine\Machine;

class UssdController
{
    public function __construct(protected Machine $machine)
    {
    }

    public function __invoke(Request $request)
    {
        $payload = [
            'sessionId' => $request->input('sessionId'),
            'msisdn' => $request->input('msisdn'),
            'input' => $request->input('text', ''),
        ];

        $response = $this->machine->handle($payload);

        return response()->json($response->toArray());
    }
}

Configuration

The Machine uses several configuration values from config/ussd.php:

  • initial_state - The starting state for new sessions
  • continuity.enabled - Enable/disable session continuity
  • continuity.timeout - Time in seconds before continuity expires
  • continuity.resume_prompt - Message shown when offering resume