Simple Factory

What is a factory? Let's imagine you order a new car; the dealer sends your order off to the factory and the factory builds your car. Your car is sent to you in its assembled form and you don't need to care about how it was made.

Similarly, a software factory produces objects for you. The factory takes your request, assembles the object using the constructor and gives them back to you to use. One of these types of Factory pattern is known as the Simple Factory. Let me show you how it works.

Firstly, we define an abstract class, which we want to extend with other classes:

<?php abstract class Notifier { protected $to; public function __construct(string $to) { $this->to = $to; } abstract public function validateTo(): bool; abstract public ...

Get Mastering PHP Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.