This article is part of the CakeDC Advent Calendar 2025 (December 4th 2025)
When you're building modern web applications, users expect things to happen instantly. They want to see notifications pop up without refreshing the page, watch live updates flow in, and get immediate feedback when something changes. This is where real-time communication comes into play, and honestly, it used to be a pain to implement.
Getting started with the Broadcasting plugin (crustum/broadcasting) is straightforward. Install it via Composer and load it in your application, and you'll have everything you need for real-time communication integrated smoothly with CakePHP 5.x.
I remember the old days when we'd write endless JavaScript code to poll the server every few seconds, hoping for new data. It was inefficient, clunky, and made our servers cry under the load. WebSockets changed everything, but they brought their own complexity. You needed separate WebSocket servers, complex connection management, and a whole new way of thinking about client-server communication.
That's exactly why I built the CakePHP Broadcasting plugin. I wanted something that felt natural to CakePHP developers, something that didn't require a deep knowledge in WebSocket protocols to understand. The idea was simple: dispatch events on the server, receive them on the client, and let the plugin handle all the messy bits in between.
The Core Idea
Broadcasting in CakePHP works on a beautifully simple concept. You have events happening in your application all the time. A user places an order, someone posts a comment, a file finishes processing. These are just regular events in your CakePHP application. Broadcasting takes these same events and pushes them out to connected clients in real-time.
Think about it like a radio station. The station broadcasts a signal, and anyone with a radio tuned to that frequency can hear it. In our case, your CakePHP application broadcasts events, and any client connected to the right channel receives them instantly. No polling, no delays, just pure real-time communication.
The plugin supports different broadcast drivers. You can use Pusher Channels if you want a hosted solution that just works. Redis is there for when you want to keep everything on your own infrastructure. You can create your own broadcast driver by implementing the BroadcastDriverInterface.
A Real Example
Let me show you how this works with a practical example. Imagine you're building an e-commerce site, and you want to notify users when their order status changes. They're sitting on the order details page, and boom, a notification appears saying their package has shipped. No page refresh needed.
First, you create an event class that implements the BroadcastableInterface. This tells CakePHP that this event should be broadcast to clients.
namespace App\Event;
use Crustum\Broadcasting\Channel\PrivateChannel;
use Crustum\Broadcasting\Event\BroadcastableInterface;
class OrderShipped implements BroadcastableInterface
{
public function __construct(
public $order
) {}
public function broadcastChannel()
{
return new PrivateChannel('orders.' . $this->order->id);
}
public function broadcastEvent(): string
{
return 'OrderShipped';
}
public function broadcastData(): ?array
{
return [
'order_id' => $this->order->id,
'tracking_number' => $this->order->tracking_number,
'carrier' => $this->order->carrier,
];
}
public function broadcastSocket(): ?string
{
return null;
}
}
Notice how we're broadcasting to a private channel. Private channels are important when you're dealing with user-specific data. You don't want user A seeing user B's order updates. The channel name includes the order ID, making it unique for each order.
Now when something happens in your application, you just broadcast the event.
use function Crustum\Broadcasting\broadcast;
public function ship($orderId)
{
$order = $this->Orders->get($orderId);
$order->status = 'shipped';
$order->shipped_at = new DateTime();
$this->Orders->save($order);
broadcast(new OrderShipped($order));
return $this->redirect(['action' => 'view', $orderId]);
}
That's it on the server side. The broadcast function takes your event and pushes it out to all connected clients. Behind the scenes, the plugin serializes the data, sends it through your configured broadcast driver, and makes sure it reaches the right channels.
How Data Flows Through Broadcasting
Understanding how your events travel from server to client helps you make better architectural decisions. When you call the broadcast function, your event starts a journey through several layers.
Your CakePHP application creates the event object and passes it to the Broadcasting system. The system extracts the channel names, event name, and payload data by calling the methods you defined on your event class. It then hands this data to the configured broadcast driver.
If you're using the Pusher driver, the plugin makes an HTTP request to Pusher's API with your event data. Pusher receives this, stores it temporarily, and immediately pushes it to all connected clients who are subscribed to that channel. The clients receive the event through their WebSocket connection and trigger your JavaScript callback.
With the Redis driver, the flow is different. Your CakePHP application publishes the event to a Redis pub/sub channel. You need a separate WebSocket server running that subscribes to these Redis channels. When it receives an event from Redis, it broadcasts it to connected WebSocket clients. This gives you full control over your infrastructure but requires running your own WebSocket server.
The queue system plays an important role too. By default, broadcasts are queued and processed asynchronously. This means your web request doesn't wait for the broadcast to complete. The broadcast job gets picked up by a queue worker and sent in the background. This keeps your application responsive even when broadcasting to many channels or when the broadcast service has a temporary slowdown.
The Client Side
On the client side, you use Laravel Echo. Yes, it says Laravel in the name, but don't let that fool you. It's just a JavaScript library that knows how to talk to various broadcasting services. It works perfectly with our CakePHP plugin.
Setting up Echo is straightforward. You include the library, configure it with your broadcasting service details, and start listening for events.
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-pusher-key',
cluster: 'your-cluster',
forceTLS: true
});
Then you subscribe to your private channel and listen for the OrderShipped event.
Echo.private(`orders.${orderId}`)
.listen('OrderShipped', (e) => {
showNotification('Your order has shipped!');
updateTrackingInfo(e.tracking_number, e.carrier);
});
The beauty here is how clean it all is. You're not managing WebSocket connections, handling reconnections, or dealing with message formats. You just say what you want to listen to, and what you want to do when you hear it.
Understanding the Pusher Protocol
The Pusher protocol has become a de facto standard for WebSocket communication. It's not just about Pusher the company anymore. The protocol defines how clients authenticate, subscribe to channels, and receive events in a standardized way. This standardization is actually great news because it means you have options.
When a client first connects, it establishes a WebSocket connection and receives a socket ID. This ID uniquely identifies that particular connection. When subscribing to private or presence channels, the client sends this socket ID along with the channel name to your CakePHP application's authorization endpoint.
Your server checks if the user can access that channel and returns a signed authentication string. The client then uses this signed string to complete the subscription. The WebSocket server verifies the signature and allows the subscription. This flow ensures that only authorized users can subscribe to private channels, and it all happens transparently through Laravel Echo.
The protocol also handles things like connection state, automatic reconnection, and channel member tracking for presence channels. These are complex problems that the protocol solves in a standard way, which is why adopting it makes sense even if you're not using Pusher's hosted service.
Beyond Pusher: Your Own Infrastructure
Here's where things get interesting. You don't have to use Pusher's hosted service. Several open-source projects implement the Pusher protocol, giving you the freedom to run your own WebSocket infrastructure.
Soketi is one such project. It's a fast, lightweight WebSocket server written in Node.js that speaks the Pusher protocol. You can run it on your own servers, point your Laravel Echo configuration at it, and everything works exactly the same. Your CakePHP Broadcasting configuration changes slightly to point to your Soketi instance instead of Pusher's servers.
'default' => [
'className' => 'Crustum/Broadcasting.Pusher',
'key' => 'your-app-key',
'secret' => 'your-app-secret',
'app_id' => 'your-app-id',
'options' => [
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http',
'useTLS' => false,
],
],
On the client side, you configure Echo similarly.
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'your-app-key',
wsHost: '127.0.0.1',
wsPort: 6001,
forceTLS: false,
disableStats: true,
});
Soketi integrates with Redis, so you get the benefits of the Redis driver with the simplicity of the Pusher protocol. Your CakePHP app publishes to Redis, Soketi reads from Redis and broadcasts to WebSocket clients. It's a solid architecture that scales well.
I'm also working on BlazeCast, a native PHP WebSocket server that implements the Pusher protocol specifically for CakePHP applications. It's designed to feel natural in a CakePHP environment, using familiar concepts and configuration patterns. BlazeCast will integrate deeply with CakePHP. It's currently in development, with plans for an initial release soon. The goal is to provide a zero-configuration WebSocket server that just works with your CakePHP Broadcasting setup.
Redis as a Broadcasting Solution
The Redis driver deserves special attention because it's the most flexible option for self-hosted solutions. When you broadcast an event using the Redis driver, the plugin publishes a message to a Redis pub/sub channel. The message contains all the event data serialized as JSON.
'redis' => [
'className' => 'Crustum/Broadcasting.Redis',
'connection' => 'default',
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => null,
'database' => 0,
],
],
The key advantage of Redis is that it decouples your CakePHP application from the WebSocket server. Your app doesn't need to know or care what's handling the WebSocket connections. It just publishes to Redis and moves on. This separation of concerns makes your architecture more resilient and easier to scale.
You can run multiple WebSocket servers all subscribing to the same Redis channels. This gives you horizontal scalability for your WebSocket infrastructure. As your user base grows, you add more WebSocket servers. Your CakePHP application doesn't change at all.
Redis pub/sub is also incredibly fast. Publishing a message takes microseconds, so there's virtually no overhead on your application. The WebSocket servers handle all the heavy lifting of maintaining connections and broadcasting to clients.
While WebSockets are the most popular approach for real-time communication, it's worth noting that you can implement server-sent events (SSE) as a broadcasting solution as well. An SSE plugin for CakePHP Broadcasting could leverage Redis pub/sub in exactly the same way as WebSocket-based drivers. In this model, your application would publish event data to Redis channels, and a separate PHP process (or worker) would stream those events to connected clients over HTTP using SSE. This approach is ideal for applications where you only need one-way communication from server to client, doesn't require extra JavaScript libraries, and works natively in all modern browsers. By utilizing Redis as the backbone for message distribution, CakePHP could offer an SSE broadcasting driver that's simple, reliable, and well-suited for many real-time dashboard and notification use cases. This is an exciting possibility for future plugin development.
The downside is you need to run a WebSocket server. Soketi works well for this, as does Laravel's Echo Server or the upcoming BlazeCast. You're trading the simplicity of a hosted solution for complete control over your infrastructure.
Authorization and Security
Private channels need authorization. When a user tries to subscribe to a private channel, Echo makes a request to your CakePHP application asking "can this user listen to this channel?" You define that logic in your channels configuration file.
use Crustum\Broadcasting\Broadcasting;
use Cake\ORM\TableRegistry;
Broadcasting::channel('private-orders.{orderId}', function ($user, $orderId) {
$ordersTable = TableRegistry::getTableLocator()->get('Orders');
$order = $ordersTable->get($orderId);
return $user->id === $order->user_id;
});
This simple function checks if the authenticated user owns the order they're trying to listen to. If they do, authorization succeeds and they can receive updates. If not, the subscription is rejected. Security sorted.
The authorization flow is interesting when you understand what's actually happening. When Echo calls your authorization endpoint, it sends the socket ID, channel name, and your application's authentication cookies or tokens. Your CakePHP application verifies the user is logged in using your normal authentication system.
If the user is authorized, your application generates a signature using your broadcast secret key, the channel name, and the socket ID. This signature proves that your server authorized this specific socket to subscribe to this specific channel. The client sends this signature to the WebSocket server, which verifies it using the same secret key.
This is important for the Pusher protocol. Whether you're using hosted Pusher, Soketi, or BlazeCast, they all work the same way. Your CakePHP application is the source of truth for who can access what. The WebSocket server just enforces the authorizations your application provides. This keeps your security logic centralized and makes it easy to update authorization rules without touching the WebSocket infrastructure.
sequenceDiagram
participant Client
participant WebSocket Server
participant CakePHP (HTTP Server)
Client->>WebSocket Server: WebSocket Connection (wss://)
WebSocket Server->>Client: HTTP 101 Switching Protocols
Note over Client,CakePHP: For private/presence channels:
Client->>CakePHP: POST /broadcasting/auth (with auth headers)
CakePHP->>CakePHP: Verify session/channel permissions
alt Authenticated
CakePHP->>Client: 200 OK (with auth token)
Client->>WebSocket Server: Subscribe with auth token
WebSocket Server->>CakePHP: Verify token validity
CakePHP->>WebSocket Server: Auth confirmation
WebSocket Server->>Client: "pusher:subscription_succeeded"
else Not Authenticated
CakePHP->>Client: 403 Forbidden
Client->>WebSocket Server: (No subscription attempt)
end
Presence Channels
Here's where things get really interesting. Presence channels not only broadcast events but also keep track of who's subscribed to them. This is perfect for features like "who's online" lists, real-time collaboration indicators, or live chat systems.
When someone joins a presence channel, everyone else already subscribed gets notified. When they leave, same thing. You even get a list of all currently subscribed users when you first join.
Echo.join(`chat.${roomId}`)
.here((users) => {
console.log('Currently in the room:', users);
})
.joining((user) => {
console.log(user.name + ' just joined');
})
.leaving((user) => {
console.log(user.name + ' just left');
});
The server-side authorization for presence channels returns user data instead of just true or false.
Broadcasting::channel('presence-chat.{roomId}', function ($user, $roomId) {
if ($user->canJoinRoom($roomId)) {
return [
'id' => $user->id,
'name' => $user->name,
'avatar' => $user->avatar_url
];
}
});
This data gets shared with all participants, so they know who they're chatting with. It's incredibly useful for building social features.
Testing Your Broadcasts
Testing real-time features used to be a nightmare. How do you verify something was broadcast? How do you check the right data was sent to the right channels? The plugin includes a testing trait that makes this straightforward.
use Crustum\Broadcasting\TestSuite\BroadcastingTrait;
class OrderTest extends TestCase
{
use BroadcastingTrait;
public function testOrderShippedBroadcast()
{
$order = $this->Orders->get(1);
$order->status = 'shipped';
$this->Orders->save($order);
$this->assertBroadcastSent('OrderShipped');
$this->assertBroadcastSentToChannel('orders.1', 'OrderShipped');
$this->assertBroadcastPayloadContains('OrderShipped', 'tracking_number', 'ABC123');
}
}
The trait captures all broadcasts during your test instead of actually sending them. Then you can make assertions about what would have been broadcast. It's fast, reliable, and lets you test your broadcasting logic without needing actual WebSocket connections or external services.
There are many diferent assertions you can use to test your broadcasts. You can assert that the right broadcasts were sent to the right channels. You can even inspect the broadcast data to verify it contains the correct information.
Wrapping Up
Building real-time features doesn't have to be complicated. The CakePHP Broadcasting plugin takes all the complexity of WebSocket management, connection handling, and message routing, and hides it behind a simple, CakePHP-friendly interface.
You dispatch events like you always do. The plugin broadcasts them. Clients receive them. Everything just works, and you can focus on building features instead of fighting with infrastructure.
Whether you're building a notification system, a live dashboard, a chat application, or anything else that needs real-time updates, broadcasting has you covered. It's the missing piece that makes modern, responsive web applications feel natural in CakePHP.
Try it out in your next project. I think you'll find that once you start broadcasting events, you'll wonder how you ever built real-time features without it.
This article is part of the CakeDC Advent Calendar 2025 (December 4th 2025)