When I think of an adapter, I think of the three prong to two prong electrical outlet thing. It allows me to plug in an electrical device that has three prongs (one with a ground) into a two prong outlet that doesn’t have a ground. The interface of the outlet is two holes and the interface of the device it has three prongs, so we need an adapter to help us. The PHP adapter pattern utilizes this very concept.
PHP Adapter Example
I’m going to keep going with the electrical outlet idea. Hopefully, this makes a little bit of sense.
In the example, the ElectricalOutlet only accepts a device that implements the TwoProngInterface. We really want to watch TV, but it implements the ThreeProngInterface, and we can’t plug it directly into the EletricalOutlet, poop. Now your mom is yelling at you, she really wants to watch Wheel of Fortune, but the TV still has no power.
Luckily, we developed an adapter! The TwoProngAdapter accepts a device that implements the ThreeProngInterface and then returns a TwoProngInterface object. We can now plug in our TV and watch Wheel of Fortune! Congrats! You saved the day and your mother still loves you.
Read through the code above and see if you can follow the logic in your head. It might help if you read it from top to bottom then bottom to top. If you’re still struggling with it, try typing it up yourself and maybe modify it a little. Learning takes time and you shouldn’t get upset if you don’t understand it right away. It sometimes takes me days, weeks, and sometimes months to understand a concept. Always take a break.
Feel free to comment below. Please comment below. Or email me? Someone has to need some help. If you do ask for help, please share with me all your code and not a sliver of it. I need to see everything that is happening. Sometimes your problem is outside the scope you are focused on.
For those of you who know me, the Wheel of Fortune story never happened, it was made up. I was always prepared.
Don’t try plugging anything with three prongs into a two prong outlet. I don’t care if you do have an adapter, it is a bad idea. The third prong is for the ground, which can help protect your device from being ruined.