What if you could change how objects are made without hunting through your whole code?
Why Factory pattern in PHP? - Purpose & Use Cases
Imagine you are building a website that sells different types of products. Each product needs a special way to be created and set up. If you write the code to create each product directly everywhere, your code becomes messy and hard to change.
Writing the creation code for each product by hand every time is slow and easy to mess up. If you want to add a new product type or change how a product is made, you have to find and update many places in your code. This can cause bugs and wastes time.
The Factory pattern solves this by putting all the product creation code in one place. You just ask the factory to make a product for you. This keeps your code clean, easy to update, and safe from mistakes.
$product = new BookProduct(); $product->setTitle('PHP Basics'); // Repeat for other products everywhere
$product = ProductFactory::create('book');
// Factory handles creation detailsIt lets you add new product types easily and keep your code organized and flexible.
Think of a coffee shop where you order different drinks. Instead of the barista remembering how to make each drink every time, they use a recipe book (factory) that tells them exactly how to prepare each one.
Manual creation scattered in code is hard to maintain.
Factory pattern centralizes object creation.
Makes adding new types simple and safe.
Practice
Factory Pattern in PHP?Solution
Step 1: Understand the role of the Factory Pattern
The Factory Pattern is designed to create objects while hiding the details of how they are created.Step 2: Compare options with the pattern's purpose
Only To create objects without exposing the creation logic to the client describes creating objects without exposing creation logic, which matches the Factory Pattern.Final Answer:
To create objects without exposing the creation logic to the client -> Option AQuick Check:
Factory Pattern = Object creation hiding [OK]
- Confusing factory pattern with database operations
- Thinking it handles input validation
- Assuming it performs calculations
Solution
Step 1: Identify typical factory method signature
Factory methods are often static so they can be called without creating an instance.Step 2: Check options for static keyword
Only public static function create() {} usespublic static function create(), which is the common factory method style.Final Answer:
public static function create() {} -> Option AQuick Check:
Factory method is usually static [OK]
- Omitting static keyword for factory methods
- Using private visibility which blocks access
- Not specifying visibility (defaults to public but less clear)
class Book { }
class ProductFactory {
public static function create($type) {
if ($type === 'Book') {
return new Book();
}
return null;
}
}
$product = ProductFactory::create('Book');
echo get_class($product);Solution
Step 1: Analyze the factory method call
The callProductFactory::create('Book')checks if the type is 'Book' and returns a newBookobject.Step 2: Check the output of get_class
Since the returned object is an instance ofBook,get_class($product)returns "Book".Final Answer:
Book -> Option CQuick Check:
Factory returns Book object, get_class = Book [OK]
- Expecting factory class name instead of product class
- Assuming null is returned
- Thinking code throws error due to missing class
class Car {}
class VehicleFactory {
public static function create($type) {
if ($type = 'Car') {
return new Car();
}
return null;
}
}Solution
Step 1: Check the if condition syntax
The condition uses=which assigns 'Car' to $type instead of comparing it.Step 2: Understand impact of assignment in condition
Assignment always returns true, so the if block always runs regardless of input, which is a logic error.Final Answer:
Using assignment (=) instead of comparison (==) in the if condition -> Option BQuick Check:
Use == for comparison, not = [OK]
- Confusing = and == in if statements
- Thinking static method is wrong here
- Assuming missing return type causes error
Solution
Step 1: Understand the Factory Pattern goal
The pattern centralizes object creation in one place, hiding details from the client.Step 2: Evaluate options for best factory design
Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input uses one factory class with a method that creates different vehicle objects based on input, which is the classic factory pattern.Step 3: Compare other options
Create separate factory classes for CarFactory, BikeFactory, and TruckFactory each with their own create method splits factories, which is more like Abstract Factory or multiple factories, not simple Factory Pattern. Create one class Vehicle with properties to switch between Car, Bike, and Truck behaviors mixes behaviors in one class, breaking single responsibility. Use global functions to create Car, Bike, and Truck objects directly uses global functions, which is not object-oriented.Final Answer:
Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input -> Option DQuick Check:
Single factory method creates varied objects [OK]
- Splitting factories unnecessarily
- Mixing multiple behaviors in one class
- Using global functions instead of classes
Ready to prove it?
Pass the test and this pattern moves unknown
