DEV Community

Cover image for A Central Clock for Laravel Web Applications with ReactPHP
Yoram Kornatzky
Yoram Kornatzky

Posted on • Edited on • Originally published at yoramkornatzky.com

3 1

A Central Clock for Laravel Web Applications with ReactPHP

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(...)));
});
Enter fullscreen mode Exit fullscreen mode

or one time,

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

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) => {

  });
Enter fullscreen mode Exit fullscreen mode

Livewire

Define in the Livewire component the listeners:

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs