PHP code example of brandonhudson / lightning

1. Go to this page and download the library: Download brandonhudson/lightning library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

brandonhudson / lightning example snippets




 = new \Lightning\App();
$mqtt->subscribe('/hello/+name', 0, function ($response) {
    $topic = $response->getRoute();
    $name = $response->attr('name');
    $message = $response->getMessage();
});
$mqtt->listen();

$mqtt->close();





 = 'mqtt.example.com';
$port = 1883;
$clientID = md5(uniqid());
$username = 'user';
$password = 'password';

// Without username/password
$mqtt = new \Lightning\App($host, $port, $clientID);

// With username/password
$mqtt = new \Lightning\App($host, $port, $clientID, $username, $password);

if (!$mqtt->connect()) {
    exit(1);
}

$mqtt->close();




 = 'mqtt.example.com';
$port = 1883;
$clientID = md5(uniqid());

$mqtt = new \Lightning\App($host, $port, $clientID);

if (!$mqtt->connect()) {
    exit(1);
}

$mqtt->publish("/hello/world", '{"hello":"world"}', 1);
$mqtt->close();



ion exampleCallback(\Lightning\Response $response) {
    $message = $response->getMessage();
}

$host = 'mqtt.example.com';
$port = 1883;
$clientID = md5(uniqid());

$mqtt = new \Lightning\App($host, $port, $clientID);

if (!$mqtt->connect()) {
    exit(1);
}

// A callback defined inline at the time of subscribing
$mqtt->subscribe('/users/+id/status', 0, function (\Lightning\Response $response) {
    $message = $response->getMessage();
});

// A callback referencing another previously defined function
$mqtt->subscribe('/users/+id/status', 0, 'exampleCallback');

// Listen will poll for new messages sent to this client
$mqtt->listen();


t = 'mqtt.example.com';
$port = 1883;
$clientID = md5(uniqid());

$mqtt = new \Lightning\App($host, $port, $clientID);

if (!$mqtt->connect()) {
    exit(1);
}

// Example with inline variable
$mqtt->subscribe('/users/+id/status', 0, function (\Lightning\Response $response) {
    $message = $response->getMessage();
    $topic = $response->getRoute();
    $id = $response->attr('id'); // fetches the id attribute from the topic
});

// Example with wildcard
$mqtt->subscribe('/users/#', 0, function (\Lightning\Response $response) {
    $message = $response->getMessage();
    $topic = $response->getRoute();
    $wildcard = $response->getWildcard(); // fetches the id attribute from the topic
});

$mqtt->listen();