Using the Factory Pattern in PHP and Laravel

16,454

Well, actually the Factory Pattern is a creational pattern which uses factory methods to deal with the problem of creating objects even without specifying a staic class, which means it create objects dynamically at the run-time. This pattern is used to deal with object creation mechanisms which lets a client class to to use a dynamic class built on run time. This pattern uses a factory method (abstract) and this method builds objects using other classes/objects depending on the request of the client class that uses the built object. Well, it's a broad thing, anyways.

Instead of thinking in design-patterns such as which pattern you should follow, try to find out the use case of your class and use them accordingly. Most probably you meant Model as classes which extends Eloquent ORM and in this case your model classes already have those methods if you extended the Eloquent ORM so you don't need to create those in your classes but to separate the business logic and DB layer you may use normal classes where you may use those classes as dependencies to call methods from your database layer classes. probably it sounds confusing anyways.

It depends on you how do you organize your directory structure but only think about SoC and that's enough to get the idea, for a clean application architectural pattern. Don't think too deep in design patterns, instead think of a clean application model, that's it. Probably this article may help you a little bit (Specially discussed using Laravel and Repository Pattern).

For Factory Pattern, you may check this simple but helpful article.

Share:
16,454
AndrewMcLagan
Author by

AndrewMcLagan

I’m a full stack Web Developer with over fifteen years experience in the industry. I concentrate on open source languages and technologies such as PHP 5.6+, Python, Javascript EMCA6, AngularJS, React, Laravel and Symfony. My strengths would be a very strong interest in the open source community and approaching web­app development from a software design perspective rather than simply being a code­monkey. Strong understanding of basic SOLID principals and the patterns that make these principles a reality. Coming from many years experience as a contract developer, keeping up­-to-­date with the open source community, tools and best practices has been paramount to my career. Also, I LOVE to code!

Updated on July 24, 2022

Comments

  • AndrewMcLagan
    AndrewMcLagan almost 2 years

    Should a factory be responsible for finding models as well as creating them?

    for example:

    If i had a product model, should its factory have methods such as:

    $product = $productFactory->findByID(32);
    
    $product = $productFactory->all();
    
    $product = $productFactory->findByName($productName);
    
    $product = $productFactory->create($data);