Using the Factory Pattern in PHP and Laravel
Asked Answered
C

1

6

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);
Cutthroat answered 7/12, 2014 at 23:30 Comment(0)
D
24

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.

Derivative answered 8/12, 2014 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.