【问题标题】:Laravel Repositories and Eloquent ModelsLaravel 存储库和 Eloquent 模型
【发布时间】:2014-08-13 00:26:51
【问题描述】:

在阅读了一些教程并主要在Laracasts 上观看视频后,我正在考虑使用Repositories 在我的网站中添加一个抽象层,该抽象层将通过一个接口注入我的ControllersRepositories 用于抽象如何检索 Model 并隐藏一些业务逻辑。使用Laravel 中提供的Bind 方法,这看起来超级简单方便。

unit tests 添加到项目中听起来非常有趣,但我不明白应该如何处理Model

例如,假设我们试图通过创建:

将旧的 User 模型隐藏在存储库后面
interface UserRepositoryInterface {
    public function getAll();
    // ...
}

那么,为了支持Laravel提供的标准User模型,定义为:

class User extends Eloquent implements UserInterface, RemindableInterface {
    // ...
}

我们创建了UserRepositoryInterfaceEloquent 实现:

class EloquentUserRepository extends UserRepositoryInterface {
    public function getAll() {
        return User::all();
    }
}

我不明白的部分是,现在Repository 不返回“通用”Model,而是返回Eloquent 模型!对我来说,其他Repositories 应该返回相同类型的Model 对我来说没有意义,如果不是这种情况,如果Models 之间根本没有相关性,那么拥有Repositories 有什么意义?退了吗?

那么Repository 模式在Laravel 中的正确用法是什么?

【问题讨论】:

  • 当我严格希望存储库返回非特定于实现的数据时,我通常会在EloquentUserRepository::getAll(); 中使用return User::all()->toArray();。但我自己有时会违反这条规则,因为返回 Eloquent 模型非常方便。 :p 我希望 Eloquent 有一个 toObject() 方法!
  • 事实是,如果你不需要那个额外的层,那就不要。必要时实施。当你这样做时,这是正确的,返回Eloquent 并不是要走的路。相反,您可以返回 array 或实现 @Unnawut 所说的内容,例如喜欢这里的安德烈亚斯:github.com/anlutro/laravel-4-core/blob/master/src/Eloquent/…
  • @Unnawut return (object) $this->toArray();

标签: php laravel model repository eloquent


【解决方案1】:

Repositories in Laravel 有助于让控制器保持精简和愚蠢。

Controllers 在交给存储库之前处理任何路由或数据解析,并以适当的格式返回数据。

Repositories 处理模型。

如果这两个函数都在同一个控制器方法中,那么您将无法确定问题是在解析输入数据还是从模型请求数据。

这种分离允许用于确保controller 将适当的数据传递给repositoryrepository 正在执行适当的验证并以正确的方式访问 model,并且所有这些都返回了正确类型的数据。

返回model 的存储库可以使用instanceof 进行类型测试:

public function testAllReturnsCollection()
{
    $collection = $this->machineRepository->all();
    $this->assertTrue($collection instanceof \Illuminate\Database\Eloquent\Collection);
}

public function testFindReturnsMachine()
{
    $model = $this->machineRepository->find($this->machineId);
    $this->assertTrue($model instanceof Machine);
}

这种类型的测试也可以使用Mocking 完成,但在使用模型时,我更喜欢使用测试数据库。

【讨论】:

  • 在查询不涉及多个不同模型的情况下,将存储库方法移动到模型怎么办?
猜你喜欢
  • 2017-08-20
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2015-03-08
  • 2014-02-05
  • 2020-09-05
相关资源
最近更新 更多