PHP

A Central Clock for Laravel Web Applications with ReactPHP

Photo by Felix Mittermeier on Pixabay

How to implement a central clock for a Laravel web application?

Why A Central Clock is Needed?

Quizzes, time tracking, online education, Pomodoro timers, auctions, and many other web applications need a central clock.

The time on this clock is what all users see on their web page.

Such a central clock has to be implemented at the server, as this is the only place where we can rely on. It needs to be transmitted to the user's web page.

Running the Clock with ReactPHP

Use ReactPHP to implement a timer, either periodic,


$timer = $loop->addPeriodicTimer($time, function() use(&$task) {
    broadcast(new TimeSignal(json_encode(...)));
});

or one time,


$timer = $loop->addTimer($time, function() use(&$task) {
    broadcast(new TimedEvent(json_encode(...))); 
});

where TimeSignal and TimedEvent are Laravel events.

Events are broadcast using Laravel Echo Server, Laravel Websockets, or Soketi. Say on a channel time.

Processing Time Signals in Front-End

JavaScript

Listen for events with Laravel Echo,

window.Echo.channel('time')
  .listen('TimeSignal', (e) => {

  })
  .listen('TimedEvent', (e) => {

  });

Livewire

Define in the Livewire component the listeners:

protected $listeners = [
    'echo:time,TimeSignal' => 'processTimeSignal',
    'echo:time,TimedEvent' => 'processTimedEvent',
];

Yoram Kornatzky

Yoram Kornatzky