📖 Scenario: You work in a car factory. Different cars are made based on the type requested. You want a simple way to create cars without repeating code.
🎯 Goal: Build a PHP program that uses the factory pattern to create different car objects based on a given type.
📋 What You'll Learn
Create a base Car class with a method getType() that returns the car type.
Create two classes Sedan and SUV that extend the Car class and return their specific types.
Create a CarFactory class with a static method createCar($type) that returns the correct car object based on the $type string.
Use the factory to create a Sedan and an SUV and print their types.
💡 Why This Matters
🌍 Real World
Factories are used in software to create objects without repeating code. This helps when you have many similar objects but want to decide which one to create at runtime.
💼 Career
Understanding the factory pattern is important for software developers because it helps write clean, maintainable, and scalable code. It is commonly used in many programming jobs.
Progress0 / 4 steps
1
Create base Car class and Sedan class
Create a class called Car with a method getType() that returns an empty string. Then create a class called Sedan that extends Car and overrides getType() to return the string "Sedan".
PHP
Hint
Use class keyword to create classes. Use extends to inherit. Override getType() in Sedan to return "Sedan".
2
Create SUV class
Create a class called SUV that extends Car and overrides the getType() method to return the string "SUV".
PHP
Hint
Similar to Sedan, create SUV class that extends Car and returns "SUV" in getType().
3
Create CarFactory class with createCar method
Create a class called CarFactory with a public static method createCar($type). Inside this method, use an if statement to return a new Sedan object if $type is "sedan", a new SUV object if $type is "suv", and null otherwise.
PHP
Hint
Use public static function createCar($type) and if statements to return the right car object.
4
Use factory to create cars and print types
Use CarFactory::createCar("sedan") to create a Sedan object and store it in $sedan. Use CarFactory::createCar("suv") to create an SUV object and store it in $suv. Then print the types of both cars using echo and the getType() method, separated by a newline.
PHP
Hint
Call CarFactory::createCar() with "sedan" and "suv". Use echo to print the types with a newline.
Practice
(1/5)
1. What is the main purpose of the Factory Pattern in PHP?
easy
A. To create objects without exposing the creation logic to the client
B. To store data in a database
C. To handle user input validation
D. To perform mathematical calculations
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 A
Confusing factory pattern with database operations
Thinking it handles input validation
Assuming it performs calculations
2. Which of the following is the correct way to define a factory method in PHP?
easy
A. public static function create() {}
B. function create() {}
C. public function create() {}
D. private function create() {}
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() {} uses public static function create(), which is the common factory method style.
Final Answer:
public static function create() {} -> Option A
Quick Check:
Factory method is usually static [OK]
Hint: Factory methods are usually static for easy access [OK]
Common Mistakes:
Omitting static keyword for factory methods
Using private visibility which blocks access
Not specifying visibility (defaults to public but less clear)
3. What will be the output of the following PHP code?
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);
medium
A. null
B. ProductFactory
C. Book
D. Error: Class not found
Solution
Step 1: Analyze the factory method call
The call ProductFactory::create('Book') checks if the type is 'Book' and returns a new Book object.
Step 2: Check the output of get_class
Since the returned object is an instance of Book, get_class($product) returns "Book".
Final Answer:
Book -> Option C
Quick Check:
Factory returns Book object, get_class = Book [OK]
Hint: Factory returns object; get_class shows its class name [OK]
Common Mistakes:
Expecting factory class name instead of product class
Assuming null is returned
Thinking code throws error due to missing class
4. Identify the error in this factory pattern implementation:
class Car {} class VehicleFactory { public static function create($type) { if ($type = 'Car') { return new Car(); } return null; } }
medium
A. Missing return type declaration
B. Using assignment (=) instead of comparison (==) in the if condition
C. Class Car is not defined
D. Factory method should not be static
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 B
Quick Check:
Use == for comparison, not = [OK]
Hint: Use == for comparison, not = assignment in conditions [OK]
Common Mistakes:
Confusing = and == in if statements
Thinking static method is wrong here
Assuming missing return type causes error
5. You want to extend a factory to create different types of vehicles: Car, Bike, and Truck. Which approach best follows the Factory Pattern principles in PHP?
hard
A. Create separate factory classes for CarFactory, BikeFactory, and TruckFactory each with their own create method
B. Use global functions to create Car, Bike, and Truck objects directly
C. Create one class Vehicle with properties to switch between Car, Bike, and Truck behaviors
D. Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input
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 D
Quick Check:
Single factory method creates varied objects [OK]
Hint: One factory method returns different objects by input [OK]
Common Mistakes:
Splitting factories unnecessarily
Mixing multiple behaviors in one class
Using global functions instead of classes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.