如果我在Laravel 5项目中使用andersao / l5-repository,我会打破控制原理的反转吗?

时间:2015-10-19 14:13:58

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

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

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

"Archive\\": "archive/"

然后我创建了一个名为Repositories的文件夹,另一个名为Contracts的文件夹。现在在Contracts文件夹中,interfacesUserRepositoryInterfaceServicesRepositoryInterface等等,在Repositories文件夹外,我的实现方式如DbUserRepository和{ {1}}等等。

我正在使用名为DbServiceRepository的{​​{1}},我将其绑定在这里:

service provider

因此,我可以在控制器中注入DataServiceProvider $this->app->bind(UserRepositoryInterface::class, DbUserRepository::class); $this->app->bind(ServiceRepositoryInterface::class, DbServiceRepository::class); Contacts,Laravel会自动将我的依赖项从IoC容器中解析出来。因此,如果将来我需要UserRepositoryInterface,我只需要创建该类并更改ServiceRepositoryInterface中的绑定,并且我的控制器中不会有任何内容。

这是我从泰勒和杰弗里那里学到的。但现在我正在尝试使用包https://github.com/andersao/l5-repository作为我的项目。

根据这一点,我将FileUserRepository我的service provider与它一起提供的BaseRepository如下:

extend

现在,我显然正在重复使用DbUserRepository namespace App; use Prettus\Repository\Eloquent\BaseRepository; class UserRepository extends BaseRepository { /** * Specify Model class name * * @return string */ function model() { return "App\\Post"; } } BaseRepositoryall()之类的所有代码和功能,但现在我正在打破控制反转原理,因为现在我必须将具体的实现注入我的控制器?

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

1 个答案:

答案 0 :(得分:2)

没有理由你仍然无法实现你的界面:

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类,你应该看到它实现了它自己的两个接口:BaseRepositoryRepositoryInterface和'幸运'php允许RepositoryCriteriaInterface表示您可以按如下方式扩展multiple interface inheritence

UserRepositoryInterface

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

interface UserRepositoryInterface extends RepositoryInterface, RepositoryCriteriaInterface { // Declare UserRepositoryInterface methods }