From the course: PHP: Design Patterns

Introducing the factory pattern - PHP Tutorial

From the course: PHP: Design Patterns

Start my 1-month free trial

Introducing the factory pattern

- In this section, we'll talk about creating objects using the factory pattern. Quite often, we want to interact with completely different objects in the same way. A perfect example is a database connection. We want to be able to get the connection regardless of whether its MySQL, Oracle, or SQL Server in the same way and do the same things with it. This becomes problematic because creating the different objects might be different. We need a way to be able to hide the implementation details of creating the object while still allowing us to create the object we need, which is exactly what the factory pattern does. This is often used with other patterns where you want to interact with different objects in the exact same way. Instead of hard coding which object you're working with instead you use a factory to create the specific object you need and interact with the results. This is particularly useful when you want to standardize interfaces. For example, when you're using various database connections you'll want to have separate logic for MySQL, another for Oracle, and another for SQL Server, but as far as your code is concerned, it's completely transparent on which one you're using. This also fits nicely with the strategy pattern, which we'll discuss later. But like all design patterns, of course there are some trade offs that we have to make. First, to make effective use of this pattern, we have to find all the places where we previously created that type of object and replace those with our new pseudo constructor. Next, since all of our objects have to want the same, we made need a lot of boiler plate code that has to be implemented in each class that can change the proper inheritance structures, but we need to design appropriately. And now let's dive into a real world example.

Contents