Skip to content

Best practices

Events

Avoid sending HTML via WebSockets.
Think of WebSockets as a notification hub: you just send a notification about a certain event, but you call a HTTP controller to update the content on the page.

Bad practice

php
use BS\XFWebSockets\Broadcast;

Broadcast::event(
    'YourAddon:UpdateAlerts',
    $alert->Receiver,
    \XF::asVisitor($alert->Receiver, static function () use ($alert) {
        return \XF::app()
            ->templater()
            ->renderTemplate('public:alert', compact('alert'));
    })
);
js
window.ws.manager.channels['visitor']
  .listen('UpdateAlerts', ( { html } ) => {
    this.updateAlertsFromHtml(html);
  });

Good practice

php
use BS\XFWebSockets\Broadcast;

Broadcast::event(
    'YourAddon:UpdateAlerts',
    ['from_alert_id' => $alert->alert_id]
);
js
window.ws.manager.channels['visitor']
  .listen('UpdateAlerts', ( { from_alert_id}  ) => {
    XF.ajax(
      'GET',
      this.loadAlertsUrl,
      { from_alert_id },
      XF.proxy(this, 'updateAlertsFromHtml')
    )
  });