0
0
PHPprogramming~30 mins

Factory pattern in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Factory Pattern in PHP
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Call CarFactory::createCar() with "sedan" and "suv". Use echo to print the types with a newline.