DEV Community

Nikola Stojiljkovic
Nikola Stojiljkovic

Posted on • Updated on

[PHP Guidelines series] Introduction and Factory Method Design Pattern

As announced here, I have started working on a series of posts related to good and bad development practices.

Introduction to the series

Since this is the first post in the series, I would like to present the format of the posts and examples.

In order to provide direct, usable examples which you can run, and to tie documentation to the code, I have decided to write this series as Markdown documentation inside a Symfony 6 project hosted on GitHub. Symfony 6 was chosen because I simply needed a comfortable framework to present the examples in, but the examples themselves are not related to any framework.

Each covered topic will have examples which you can read, run, or play with directly.

The intended way of using the repository is to use it as an online learning, reference and examples resource, but you are free to clone the repo if you want to actually run the examples. You can either run it locally, if you have PHP 8.1 installed and active, or in a provided Docker container.

The repository is available on GitHub at: https://github.com/constup/php-guidelines

Factory Method Design Pattern

The first covered topic is the Factory Method Design Pattern: https://github.com/constup/php-guidelines/tree/master/src/DesignPatterns/Creational/FactoryMethod

Factory Method Design Pattern is one of the 23 well known design patterns covered in many books and online resources. However, after a deep dive into the theory and practice, I've came to some interesting conclusions.

The knowledge which can be found on the first page of Google search results, has significantly degraded.

Top results from websites dedicated to explaining design patterns are either incomplete, cover only one aspect of the pattern, or are simply wrong. The most important part is - each source explains the Factory Method pattern differently, which can be very confusing to students and new developers.

My intention with this post was to provide a more complete picture, covering the Factory Method design pattern from multiple angles with multiple different implementations.

Factory Method Design Pattern, although well known, is not as good for your code as you might think.

I have covered the theory, provided examples, explained in detail why it's bad and provided a practical alternative. Motivation behind this is to try and root out bad development practices, regardless of whether they are well known and widely used or not.

I hope that you will find this resource helpful. Feedback is welcome.

If you liked the article,...
Image description

Top comments (0)