A factory method in PHP is a method that creates and returns instances of objects of a specific class, without exposing the object creation logic to the client code. This allows the client code to create objects without having to know the details of the object creation process.
Here’s an example of a factory method:
interface Vehicle {
public function getName();
}
class Car implements Vehicle {
public function getName() {
return "Car";
}
}
class Motorcycle implements Vehicle {
public function getName() {
return "Motorcycle";
}
}
class VehicleFactory {
public static function create($type) {
switch($type) {
case 'car':
return new Car();
case 'motorcycle':
return new Motorcycle();
default:
throw new Exception("Invalid vehicle type.");
}
}
}
$vehicle1 = VehicleFactory::create('car');
$vehicle2 = VehicleFactory::create('motorcycle');
echo $vehicle1->getName(); // Output: Car
echo $vehicle2->getName(); // Output: Motorcycle
In this example, we define an interface called “Vehicle” that defines a method called “getName”. We then define two classes that implement the “Vehicle” interface: “Car” and “Motorcycle”.
We also define a “VehicleFactory” class that has a static method called “create”. The method takes a “type” parameter, which determines which type of vehicle to create. The method then returns an instance of the appropriate class.
Finally, we use the “VehicleFactory” class to create instances of the “Car” and “Motorcycle” classes, and call the “getName” method on each instance to get the name of the vehicle.
The factory method pattern can be very useful for creating objects in a flexible and modular way. By using a factory method, you can decouple the object creation process from the client code, and make it easier to modify or extend the object creation process in the future.