php - 如果我在 Laravel 5 项目中使用 andersao/l5-repository 会破坏控制反转原则吗?

标签 php laravel laravel-5 inversion-of-control

我是 Laravel 开发新手,我正在尝试像一名优秀的程序员一样理解和应用 SOLID 原则。所以我最近学习并应用了 laravel 中的存储库模式。

为此,我创建了一个目录存档并使用 psr-4 加载它,如下所示:

"Archive\\": "archive/"

然后我创建了一个名为 Repositories 的文件夹和另一个名为 Contracts 的文件夹。现在在 Contracts 文件夹中我有 interfacesUserRepositoryInterfaceServicesRepositoryInterface 等等,在 Repositories 文件夹之外, 我有 DbUserRepositoryDbServiceRepository 等实现。

我正在使用一个名为 DataServiceProviderservice provider ,我像这样绑定(bind)它们:

$this->app->bind(UserRepositoryInterface::class, DbUserRepository::class);
$this->app->bind(ServiceRepositoryInterface::class, DbServiceRepository::class);

这样我就可以在我的 Controller 中注入(inject) Contacts,比如 UserRepositoryInterfaceServiceRepositoryInterface,Laravel 会自动从 IoC 容器中解析我的依赖项.因此,如果将来我需要一个 FileUserRepository,我只需要创建该类并更改我的 service provider 中的绑定(bind),我的 Controller 就不会出现任何问题。

这是我从 Taylor 和 Jeffrey 那里学到的。但现在我正在尝试使用一个包 https://github.com/andersao/l5-repository对于我的项目。

据此,我将扩展我的 DbUserRepository 与它附带的 BaseRepository,如下所示:

namespace App;

use Prettus\Repository\Eloquent\BaseRepository;

class UserRepository extends BaseRepository {

    /**
     * Specify Model class name
     *
     * @return string
     */
    function model()
    {
        return "App\\Post";
    }
}

现在,显然我重用了 BaseRepository 附带的所有代码和功能,例如 all()panginate($limit = null, $ columns = ['*'])find($id) 等等,但现在我打破了控制反转原则,因为现在我必须将具体实现注入(inject)到我的 Controller 中?

我仍然是一名新手开发人员,并试图理解所有这些,并且在解释事情时可能在问题的某个地方出错了。在使用包的同时又能在 Controller 中保持松散耦合的最佳方法是什么?

最佳答案

没有理由你仍然不能实现你的接口(interface):

namespace App;

use Prettus\Repository\Eloquent\BaseRepository;

class DbUserRepository extends BaseRepository implements UserRepositoryInterface {

    /**
     * Specify Model class name
     *
     * @return string
     */
    function model()
    {
        return "App\\Post";
    }
}

但是,您现在遇到了一个问题;如果你换掉你的实现,你的 UserRepositoryInterface 中没有任何内容表明 BaseRepository 方法也必须被实现。如果你看一下 BaseRepository 类,你应该看到它实现了它自己的两个接口(interface):RepositoryInterfaceRepositoryCriteriaInterface 和 'luckily' php 允许多接口(interface)继承,这意味着您可以按如下方式扩展您的UserRepositoryInterface:

interface UserRepositoryInterface extends RepositoryInterface, RepositoryCriteriaInterface {

  // Declare UserRepositoryInterface methods

}

然后您可以正常绑定(bind)和使用您的界面:

$this->app->bind(UserRepositoryInterface::class, DbUserRepository::class);

关于php - 如果我在 Laravel 5 项目中使用 andersao/l5-repository 会破坏控制反转原则吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33216727/

相关文章:

php - Laravel 在 hasManyThrough 中包含用户的帖子

Laravel Nova 指标过滤

php - 如何将 id 传递到 foreach 循环中以获取所有相关记录?

javascript - Laravel 验证使用点数组语法使用 JQuery 查找输入名称

php - "H"信件未发送至电报机器人

php - Laravel:Eloquent Eager Loading 关系的选择

laravel - ReflectionException-中间件类不存在Laravel 5.2

php - 如何提取所有在laravel中重复的行?

php - 使用php将复选框的所有可能存储在mysql数据库中

php - 摘要中的错误应该与