laravel存储库-为什么需要调用接口而不是直接调用存储库文件?

问题描述

我已经了解了存储库模式。因此,我创建了UserRepositoryInterface.PHP文件

namespace App\Interfaces;

use Prettus\Repository\Contracts\RepositoryInterface;

interface UserInterface extends RepositoryInterface
{
    // Code
}

然后我创建了UserRepository.PHP

<?PHP

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use App\Interfaces\UserInterface;

class UserRepository extends BaseRepository implements UserInterface
{
    public function model()
    {
        return User::class;
    }
}

最后,我将接口绑定到RepositoryServiceProvider.PHP中的类

    public function boot()
    {
        $this->app->bind(UserInteface::class,UserRepository::class);
    }

在将存储库注入类时,我想知道应该注入UserRepository还是UserInterface。我已经读过UserInterface应该被注入,但是我不明白为什么我们不仅仅使用UserRepository,它会更快,不是吗? 有人帮忙吗?

谢谢。

解决方法

注入接口而不是具体的类的全部目的是使change/extend/maintenance/test更容易。

现在,在您的情况下,您已经在某种控制器方法或构造函数中注入了UserRepositoryInterface。但是UserRepository类仍然与Eloquent的代码紧密结合(因为它扩展了Eloquent的类)。

现在想象您正在从另一个提供者/来源(可能是通过API调用从第三方)获得用户。您可以在单独的类\App\Repositories\ApiCallUserRepository中设置该代码(例如)。

您还将设置ApiCallUserRepository(新创建的类)以实现\App\Interfaces\UserInterface

当您拥有所有这些时,只需更改提供者即可 换句话说,当接口被依赖注入时,您只需要指示应用程序使用哪个具体类即可。同样,这意味着应该从两个具体的类(存储库提供程序)向使用存储库的类(即控制器的方法)提供相同的数据结构,或者至少接收数据类/代码应该期望提供的结构是否是Eloquent Collection,是否是Eloquent Collection。一些其他类型的集合。

这样,您就可以很好地设置服务来吸引用户。而且,您可以轻松地从想要获得用户的提供商中进行选择。

这还不是全部:在执行时(即发出请求时),您可以设置适当的具体类或根据任何任意规则制作其他代码。在Laravel的服务容器中,检查when()->needs()->give(),但我也热烈建议您再次浏览完整的(页面)docs

也不要限制自己,而是阅读有关DI的其他常规和特定文章:

php-di

designpatternsphp

Symfony DependencyInjection Component

laminas-di

也许所有这些似乎都是开销,但实际上,这是以良好,标准,可维护和可测试的方式扩展应用程序的良好起点。