Learn Adapter Design Pattern in PHP With Example

Mohasin Hossain
3 min readMar 1, 2024

--

An adapter allows you to convert or translate one interface for use with another.

I am assuming that you already guess the adapter design pattern by seeing the image above. Let’s drive into deep.

Let’s imagine you have a memory card with some data and you need that data in your laptop too. Now how you can get the data? Answer is Easy! By using an adapter. Yes, this what adapter design pattern actually do.

You need another example of real life programming project concept, right? Let’s begins the game!

Here is a Person class and a person can read a book by opening the book and can to to next page by turn the page. Nice!

But what about any e-book like Kindle or Nook. Can our person class handle this? can the person read e-book too? let’s see.

See! Person class no longer working because the interface (BookInterface) we are using for the Person class is not matched with the interface (eReaderInterface) we pass, right? So how can we fix this, now we need an adapter class to make eReaderInterface adaptable or you can say compatible with BookInterface. Let’s create.

Now, person can also read e-reader too that was not supported earlier. Great! And if you want to add any other e-reader like Nook just create a Nook class and pass it through eReaderAdapter class. That’s it. Can you see how we normalized this. we translate original interface (bookInterface) methods to the new one (eReaderInterface). Without changing a single line of code in our Person class we can handle the problem with an Adapter class. we wrap up unsupported class (Kindle/can be any client) in an adapter and pass this into read method method. Hope you understand!

One more thing you can thin k you are using any third party API or service and that service isn't compatible for your existing system now how you fix it? Simple, by using Adapter design pattern.

Bonus: If you are familiar with Laravel and used file system you see you can use many driver like local, Amazon S3 and so on. Do you know how? Adapter is the answer ;)

Hoping you found this helpful!

--

--

Mohasin Hossain
Mohasin Hossain

Written by Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux

Responses (2)