Today I refactored some code, And for the first time ever I wrote a factory class.

I have a class that calls a specific service on the web. I had that class directly referenced in other parts of my code. What I realized though is that someday, we may want to use a different service instead of the one we’re using now.

I needed a way to make the code more flexible in case we ever switch services.

I had heard and read about factory classes before, but the concept was a little fuzzy to me. But here was a perfect opportunity to use that pattern. Once I realized what I needed, it just clicked. In about 15 minutes, I had refactored my code, And now it not only uses a factory class, it also uses an interface-another concept that I was never totally clear on until recently.

After I had the factory class, and interface in place, PHP Storm was complaining that I was passing the wrong object type into a function. It only took me a moment or two to realize that what I needed to do was subclass. Something else that until today I have never needed to do. Sure, I understood what subclassing is, But I never saw a practical use for it.

So in one day the concepts that have come together are:

  • Factory Class
  • Interface
  • Abstract Base Class

If you ask me, I’d say it was a pretty good day.

Factories and base classes