Bridge Pattern in PHP With Example.

Imagine you have a service responsible for returning search results and you want to use this service in your APIs, Admin area, and Homepage but you want to replace blank spaces with a dash in API response (or other changes) and not in another part of your application.

We gonna use Bridge Pattern to achieve this but before getting started please have a look at the Bridge pattern class diagram

Let’s create an interface as mentioned in the class diagram.

Now it’s time to create classes implementing our SearchResultFormatter interface.

This is the main Formatter class that we use in Admin and Homepage
This is the API Formatter class which we use for Formatting response in API.

As you see, we created our Formatter classes! now it’s time to use these Formatters in our service.

this is an abstract class that takes care of Formatters and our SearchService must extend it.

We are almost done! let's use SearchService with different Formatters.

I’ve tried to keep things simple, It’s better to create new services for each API, Homepage, and Admin.

I pushed this example on my Github and you can check the source code there.

Backend Developer, Flexitarian, Technology enthusiast