Stay Tuned withour Blogs andLatest Updates !

Design pattern(Factory Method) in PHP

There are numerous ways to structure the code and project for you web application, and you can put as much or as little thought as you like into architecting. But it is usually a good idea to follow to common patterns because it will make your code easier to manage and easier for others to understand.
Factory

Definition: “The Factory Method pattern is a design pattern used to define a runtime interface for creating an object. It’s called a factory because it creates various types of objects without necessarily knowing what kind of object it creates or how to create it.”

One of the most commonly used design patterns is the factory pattern. In this pattern, a class simply creates the object you want to use. Consider the following example of the factory pattern:

This code uses a factory to create the Automobile object. There are two possible benefits to building your code this way, the first is that if you need to change, rename, or replace the Automobile class later on you can do so and you will only have to modify the code in the factory, instead of every place in your project that uses the Automobile class. The second possible benefit is that if creating the object is a complicated job you can do all of the work in the factory, instead of repeating it every time you want to create a new instance.

Using the factory pattern isn’t always necessary (or wise). The example code used here is so simple that a factory would simply be adding unneeded complexity. However if you are making a fairly large or complex project you may save yourself a lot of trouble down the road by using factories.