Using the Factory Pattern in PHP and Laravel Using the Factory Pattern in PHP and Laravel laravel laravel

Using the Factory Pattern in PHP and Laravel


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.