gpt4 book ai didi

laravel - 关于在 Laravel 中为每个模型创建存储库

转载 作者:行者123 更新时间:2023-12-02 03:34:48 25 4
gpt4 key购买 nike

我刚刚开始学习 Laravel 存储库,很快我想到了一个关于存储库和模型的问题。

假设我在 app/models 目录中有 20 个模型。这是否意味着如果我想让我的应用程序在切换 ORM 时更加灵活,我需要创建 20 个不同的存储库?我应该选择什么时候创建存储库?

最佳答案

Does this mean that I need to make 20 different repositories if I want to make my application more flexible when switching ORMs for example?

没有。它不是。您可以实现具有所有基本持久性功能的基本存储库,例如查找、保存、全部等。

然后您可以使用反射来简单地包装对底层模型对象的调用。

class BaseRepository
{
private $type;
public function constructor($type){
$this->type = $type;
}

/**
* all
*
* @return array all the elements from datastore
*/
public function all()
{
$reflectionMethod = new \ReflectionMethod($this->type, 'all');

return $reflectionMethod->invoke(null);
}
}

然后在您的 Controller 中或任何您可以使用指定类型初始化存储库的地方,如下所示:

$repo = new BaseRepo('\FullyQualified\ModelNamespace\Model');
var_dump($repo->all());

When should I choose to create repository?

回答这个有点多毛。关于存储库模型在编写应用程序时的真正值(value)有很多争论,尤其是当您已经对 Laravel 的模型层进行了大量抽象时。

我会根据我对几个问题的回答来评估是否使用存储库模式:

1. How likely is this app to be a long term project? (The longer you expect the code to be around the more benefit you will gain from using a repository)
2. What level of abstraction is the stakeholder willing to pay for? (Repositories add flexibility, but cost more up front in terms of cost and time.)

一般来说,除了最琐碎的应用程序之外,我认为存储库模式值得预先付出额外的费用,你的工作是帮助利益相关者了解从长远来看,维护成本会大大降低、测试和更改。

关于laravel - 关于在 Laravel 中为每个模型创建存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24294728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com