The factory pattern helps create objects without needing to know the exact class. It makes code easier to change and organize.
Factory pattern in PHP
<?php class Factory { public static function create($type) { switch ($type) { case 'A': return new ClassA(); case 'B': return new ClassB(); default: throw new Exception('Unknown type'); } } } class ClassA { public function say() { return "I am Class A"; } } class ClassB { public function say() { return "I am Class B"; } }
The factory method is usually static so you can call it without creating the factory object.
Use a switch or if-else to decide which class to create based on input.
<?php $obj = Factory::create('A'); echo $obj->say();
<?php $obj = Factory::create('B'); echo $obj->say();
<?php try { $obj = Factory::create('C'); } catch (Exception $e) { echo $e->getMessage(); }
This program uses the factory to create different vehicle objects. It calls their drive method to show what they do. If an unknown type is requested, it shows an error message.
<?php class Factory { public static function create($type) { switch ($type) { case 'Car': return new Car(); case 'Bike': return new Bike(); default: throw new Exception('Unknown vehicle type'); } } } class Car { public function drive() { return "Driving a car"; } } class Bike { public function drive() { return "Riding a bike"; } } try { $vehicle1 = Factory::create('Car'); echo $vehicle1->drive() . "\n"; $vehicle2 = Factory::create('Bike'); echo $vehicle2->drive() . "\n"; $vehicle3 = Factory::create('Plane'); echo $vehicle3->drive() . "\n"; } catch (Exception $e) { echo $e->getMessage() . "\n"; }
The factory pattern helps keep your code flexible and easy to update.
It separates object creation from usage, so you can add new classes without changing much code.
Always handle unknown types to avoid errors.
The factory pattern creates objects without exposing the creation logic.
It helps manage many related classes with a simple interface.
Use it to keep your code clean and easy to maintain.
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
