php-mqtt/client

Uncaught Error: Class 'PhpMqtt\Client\MqttClient' not found

ChR-iSz opened this issue · 4 comments

Don't know, whites wrong here:

My PHP:

<?php

require_once(realpath($_SERVER["DOCUMENT_ROOT"]) .'/../vendor/autoload.php');

use PhpMqtt\Client\Examples\Shared\SimpleLogger;
use PhpMqtt\Client\Exceptions\MqttClientException;
use PhpMqtt\Client\MqttClient;
use Psr\Log\LogLevel;

$server   = '127.0.0.1';
$port     = 1234;
$clientId = 1;

$mqtt = new MqttClient($server, $port, $clientId);
$mqtt->connect();
$mqtt->publish('php-mqtt/client/test', 'Hello World!', 0);
$mqtt->disconnect();

I got this trace error:

Fatal error: Uncaught Error: Class 'PhpMqtt\Client\MqttClient' not found in /var/www/html/api/Dashboard.php:21
Stack trace:
#0 {main}

There are three possible issues here:

  • your require_once for the autoload.php is wrong (would probably throw a different error though)
  • the Composer package php-mqtt/client is not installed correctly (have you verified, it is there in the vendor directory?)
  • you did not run composer dump-autoload to update the autoload.php

Hello, I have the same issue and I have a vendor directory with php-mqtt\client in it and have ran composer dump-autoload.

Here is the code I have copied from the publish section.

<?php 
    $server   = 'test.mosquitto.org';
    $port     = 1883;
    $clientId = 'test-publisher';

    $mqtt = new \PhpMqtt\Client\MqttClient($server, $port, $clientId);
    $mqtt->connect();
    $mqtt->publish('php-mqtt/client/test', 'Hello World!', 0);

    $mqtt->subscribe('php-mqtt/client/test', function ($topic, $message) {
        echo sprintf("Received message on topic [%s]: %s\n", $topic, $message);
    }, 0);
    $mqtt->loop(true);
    
    $mqtt->disconnect();
?>

You are not including the vendor/autoload.php as written above.

It is working now, big thanks.