From the course: PHP: Design Patterns

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Exploring a use case for the publish/subscriber pattern

Exploring a use case for the publish/subscriber pattern - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Exploring a use case for the publish/subscriber pattern

- Our starting example is pretty simple. We have three components, A, B, and C. After a particular event occurs in object A, we want the same event to occur in object B and object C. The default way to handle this is to wire each individually. So when we look at this in the browser, we can see that each one is called sequentially, just as we had designed. So Component A did something, then Component B, then Component C. Unfortunately, this doesn't scale as we add more components. So let's take a different approach. In this approach, let's start with the same three components. Component A, B, and C but we'll add a fourth, we'll add a dispatcher. This dispatcher implements a singleton to make sure that there is one and only one instance, but more importantly, it implements both a subscribe and publish method. The subscribe method takes two inputs, an object being watched and the object actually doing the watching. We call these "listeners." We store that relationship for later. The…

Contents