Using the Factory Pattern in PHP and Laravel
Should a factory be responsible for finding models and creating them?
eg:
If I had a product model if its factory has methods like:
$product = $productFactory->findByID(32);
$product = $productFactory->all();
$product = $productFactory->findByName($productName);
$product = $productFactory->create($data);
source to share
Well actually Factory Pattern
it creational pattern
is that uses factory methods to solve the problem of creating objects even without specifying the staic class, which means it dynamically creates objects in run-time
. This template is used to work with object creation mechanisms that allow a client class to use a dynamic class that is built at runtime. This pattern uses a factory (abstract) method and this method builds objects using other classes / objects depending on the request of the client class that uses the constructed object. Well, that's actually anything.
Instead of thinking about design patterns, such as a pattern that you should follow, try to figure out an example of your class's usage and use it accordingly. Most likely you meant Model
as classes that extend the Eloquent
ORM, in which case your model classes already have these methods if you extended Eloquent ORM
, so you don't need to create them in your classes, but to separate the business of the logic and the DB layer, you can use regular classes where you can use these classes as dependencies to call methods from your database layer classes. it probably sounds confusing anyway.
It's up to you how you organize your directory structure, but think only of SoC and that's enough to get this idea, for a clean architectural drawing application. Don't think too deeply in design patterns, instead think about the pure application model, what it is. Probably, this article can help you a little bit (especially discussed using Laravel
and Repository Pattern
).
For Factory Pattern
you can check out this simple yet helpful article.
source to share