Simple factory simply creates an instance without exposing any instantiation details to the client.
interface Book
{
public function getName(): string;
}
class FantasyBook implements Book
{
public function __construct(private string $name) {}
public function getName(): string
{
return $this->name;
}
}
class BookFactory
{
public static function make($name): Book
{
return new FantasyBook($name);
}
}
$book = BookFactory::make("Lord of the Rings");
echo $book->getName();
Lord of the Rings
Example uses Constructor Property Promotion (PHP 8.0) syntax. Which declares and assigns class properties at the same time.
public function __construct(private string $name) {}
It's similar to Member initializer lists in C++.