laravel 5中的模型和存储库有什么区别?

zik*_*hir 5 laravel

我想知道laravel 5中Models和Repository之间的区别是什么.两者是否相同以及存储库的好处是什么.

mbo*_*ood 10

模型和存储库不一样.

文档 - Models allow you to query for data in your tables, as well as insert new records into the table.这就是说,模型打开对数据库表的访问.它还允许您与其他模型相关联以提取数据,而无需编写单个查询.

存储库允许您处理模型而无需在控制器内部编写大量查询.反过来,如果出现任何错误,保持代码更整洁,模块化并更容易调试.

您可以通过以下方式使用存储库:

public function makeNotification($class, $title, $message)
{
    $notification = new Notifications;
    ...
    $notification->save();
    return $notification->id;
}

public function notifyAdmin($class, $title, $message)
{
    $notification_id = $this->makeNotification($class, $title, $message);
    $users_roles = RolesToUsers::where('role_id', 1)->orWhere('role_id', 2)->get();
    $ids = $users_roles->pluck('user_id')->all();
    $ids = array_unique($ids);
    foreach($ids as $id) {
        UserNotifications::create([
            'user_id' => $id,
            'notification_id' => $notification_id,
            'read_status' => 0
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

在控制器内部:

protected $notification;

public function __construct(NotificationRepository $notification)
{
    $this->notification = $notification;
}

public function doAction()
{
    ...
    $this->notification->notifyAdmin('success', 'User Added', 'A new user joined the system');
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 但是如果我们把所有这些都写在 Model 中,控制器仍然会保持干净。那么存储库对模型的具体用途是什么? (5认同)
  • 听起来不错,但是您的存储库代码与 Eloquent 和 Laravel 耦合。我认为拥有存储库很好。但不是为了便携性,没有。 (4认同)
  • @AmitShah 使用存储库可以让您将业务逻辑与数据库层解耦。将 2 混合在一起是愚蠢的。尤其是当您从 Eloquent 转向不同的 ORM 或数据存储方法时。我建议您阅读以下内容:http://shawnmc.cool/the-repository-pattern (2认同)

sam*_*x01 6

存储库基本上允许您将业务逻辑与数据库层解耦。

虽然您的雄辩模型知道如何查找给定实体的所有记录,但您的存储库可以将其包装在特定于业务的逻辑中:

// Eloquent
$users = User::where('active', true)->get();

// Repository
$users = $this->userRepository->getAll(true);

class UserRepository {
    protected $model;

    public function __construct(User $model)
    {
        $this->model = $model;
    }

    public function getAll($active = false)
    {
        if ( $active === true )
        {
            return $this->model->where('active', true)->get();
        }

        return $this->model->all();
    }
}
Run Code Online (Sandbox Code Playgroud)

这为您提供了可测试性和关注点分离,您的应用程序不再与特定实现紧密耦合。这样做,例如,切换与 JSON API 对话的雄辩持久性就会变得更简单。当您将一个接口绑定到控制器(例如 UserRepositoryInterface)时,这会变得更容易,因为您只需更新服务提供程序中的一行即可更新该接口的所有使用。

不过,与任何事情一样,这是否适合您的应用程序取决于您。存储库为您的应用程序增加了另一层复杂性,而小型 CRUD 应用程序实际上并不需要这种复杂性。