简体   繁体   English

在PHP和Laravel中使用工厂模式

[英]Using the Factory Pattern in PHP and Laravel

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);

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 . 好吧,实际上Factory Pattern是一种creational pattern ,它使用工厂方法来处理创建对象的问题,即使没有指定staic类,这意味着它在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. 很可能你的意思是Model作为扩展Eloquent ORM的类,在这种情况下,如果扩展了Eloquent ORM ,你的模型类已经有了这些方法,所以你不需要在类中创建那些,而是将业务逻辑和数据库层分开可以使用普通类,您可以使用这些类作为依赖项从数据库层类调用方法。 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. 这取决于你如何组织你的目录结构,但只考虑SoC ,这足以让我们了解干净的应用程序架构模式。 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 ). 可能这篇文章可能对你有所帮助 (特别是使用LaravelRepository Pattern讨论)。

For Factory Pattern , you may check this simple but helpful article. 对于Factory Pattern ,您可以查看这篇简单但有用的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM