在 PHP 和 Laravel 中使用工厂模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27349154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the Factory Pattern in PHP and Laravel
提问by AndrewMcLagan
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);
回答by The Alpha
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.
嗯,实际上Factory Pattern
is acreational pattern
使用工厂方法来处理创建对象的问题,即使没有指定 staic 类,这意味着它在run-time
. 此模式用于处理对象创建机制,该机制允许客户端类使用在运行时构建的动态类。此模式使用工厂方法(抽象),该方法根据使用构建对象的客户端类的请求使用其他类/对象构建对象。嗯,无论如何,这是一个广泛的事情。
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.
与其考虑应该遵循哪种模式等设计模式,不如尝试找出类的用例并相应地使用它们。很可能你的意思是Model
作为扩展Eloquent
ORM 的类,在这种情况下,如果你扩展了Eloquent ORM
,你的模型类已经拥有这些方法,所以你不需要在你的类中创建这些方法,而是将业务逻辑和数据库层分开,你可以使用普通类您可以使用这些类作为依赖项来调用数据库层类中的方法。无论如何,这听起来可能令人困惑。
It depends on you how do you organize your directory structure but only think about SoCand 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 youa little bit (Specially discussed using Laravel
and Repository Pattern
).
这取决于你如何组织你的目录结构,但只考虑SoC,这足以获得一个干净的应用程序架构模式的想法。不要在设计模式中考虑太深,而要考虑一个干净的应用程序模型,仅此而已。可能这篇文章可能会对您有所帮助(特别讨论使用Laravel
和Repository Pattern
)。
For Factory Pattern
, you may check thissimple but helpful article.
对于Factory Pattern
,您可以查看这篇简单但有用的文章。