Skip to content

Mohcin Bounouara

Thoughts about software engineering and life

Understanding Factory Design Patterns in PHP

Design Patterns are solutions for common problems in the software development field, you can know things in detail using this resource.

I will try to explain in this blog post my understanding of the Factory pattern based on Laravel codebases and also functions that we are mostly using when we work using Laravel

What is a Factory pattern in simple terms?

It is a solution created by software engineers during the last years to solve those main problems particularly:

  • When we use direct object instantiate we are making things difficult to change and maintain in our codebase, so creating a Factory class that centralizes the object creation, encapsulates the instantiation process, and can easily be modified or extended without affecting the rest of the code.
  • Repeating some complex object on the entire project will cause a slow working system, and a system that is hard to maintain, the factory handles all the complicated steps, so your main code stays simple.
  • Changing object creation in multiple places will surely lead to mistakes. However, you only need to use the factory to update the creation logic in one place, reducing errors and making your code cleaner.

In Laravel, the Factory design pattern is used for generating test data through model factories for example. This is useful for testing and seeding the database.

Also in Laaravel it’s used to generate views in the controllers