You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+105
Original file line number
Diff line number
Diff line change
@@ -249,6 +249,111 @@ $connectionSettings = (new \PhpMqtt\Client\ConnectionSettings)
249
249
->setTlsAlpn(null);
250
250
```
251
251
252
+
### Hooks
253
+
254
+
The client includes a flexible and powerful hook system to allow custom behaviors during different stages of the MQTT lifecycle. Hooks are registered using closures and can be added or removed dynamically at runtime.
255
+
256
+
> 💡 All hooks receive the MQTT client instance (`MqttClient`) as their first argument, allowing full access to the client's capabilities from within the hook.
257
+
258
+
> 💡 Each hook is executed in a `try-catch` block to ensure no individual exception can crash the loop or hook processing.
259
+
260
+
#### Loop Event Hooks
261
+
262
+
Called on each iteration of the MQTT client's loop. This hook is especially useful to implement timeouts or other deadlock-prevention logic.
263
+
264
+
##### Register
265
+
266
+
```php
267
+
$callback = function (MqttClient $mqtt, float $elapsedTime) {
268
+
echo "Running for {$elapsedTime} seconds already.";
269
+
};
270
+
271
+
$mqtt->registerLoopEventHandler($callback);
272
+
```
273
+
274
+
##### Unregister
275
+
276
+
```php
277
+
$mqtt->unregisterLoopEventHandler($callback); // Unregister specific event handler
278
+
$mqtt->unregisterLoopEventHandler(); // Unregister all event handlers
279
+
```
280
+
281
+
#### Publish Event Hooks
282
+
283
+
Triggered every time a message is published to the broker. This hook is useful to implement centralized logging or metrics.
284
+
285
+
##### Register
286
+
287
+
```php
288
+
$callback = function (
289
+
MqttClient $mqtt,
290
+
string $topic,
291
+
string $message,
292
+
?int $messageId,
293
+
int $qualityOfService,
294
+
bool $retain
295
+
) {
296
+
echo "Published to [{$topic}]: {$message}";
297
+
};
298
+
299
+
$mqtt->registerPublishEventHandler($callback);
300
+
```
301
+
302
+
##### Unregister
303
+
304
+
```php
305
+
$mqtt->unregisterPublishEventHandler($callback); // Unregister specific event handler
306
+
$mqtt->unregisterPublishEventHandler(); // Unregister all event handlers
307
+
```
308
+
309
+
#### Message Received Hooks
310
+
311
+
Executed when a message is received from the broker as part of a subscription. This hook is useful to implement centralized logging or metrics.
0 commit comments