Skip to content

Instantly share code, notes, and snippets.

@mgdm
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgdm/e9f7b287852addf6e22b to your computer and use it in GitHub Desktop.
Save mgdm/e9f7b287852addf6e22b to your computer and use it in GitHub Desktop.
Mosquitto\Client subclassing

Subclassing Mosquitto\Client

The Client class in the Mosquitto extension is a heavy user of callbacks. As the class is currently implemented, you need to individually assign the various callbacks manually. For example:

function messageHandler($message) {
  var_dump($message);
}

$client = new Mosquitto\Client();
$client->onMessage('messageHandler');

You could use closures for the same purpose, or indeed anything callable:

$client = new Mosquitto\Client();
$client->onMessage(function($message) {
  var_dump($message);
});

The Client class is subclassable as well. However, if you want to do this, you still need to wire up the callbacks manually:

class MyClient extends Mosquitto\Client {
  public function __construct() {
    parent::__construct();
    $this->onMessage([$this, 'messageHandler']);
  }
  
  public function messageHandler($message) {
    var_dump($message);
  }
}

$client = new MyClient();

I'd like to make it easier and avoid this step, so what I"m considering doing is using magic methods prefixed with __, the same as the ones similarly available in normal classes in PHP. For example:

class MyClient extends Mosquitto\Client {
  public function __onMessage($message) {
    var_dump($message);
  }
}

$client = new MyClient();

This would have exactly the same effect as the previous class. The existing onMessage() method will still work, and if called will overwrite the built-in method. This would apply for all the callbacks: __onConnect, __onDisconnect, __onLog, __onMessage, __onSubscribe, and __onUnsubscribe.

Does that seem reasonable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment