【问题标题】:How to Effectively use Laravel Repository pattern Binding如何有效地使用 Laravel Repository 模式绑定
【发布时间】:2020-11-20 14:43:57
【问题描述】:

我对 laravel 中的存储库模式有一个疑问,我将在我的项目中使用存储库模式,但我的项目像电子商务网站(如 Flipkart、ebay、amazon..),目前我有 80 多个表。将来我会添加很多表,那么如何有效地处理提供者中的绑定方法? (我的示例代码如下所示)

class RepoServiceProvider extends ServiceProvider
{

    public function register(){
        $this->app::bind(
              'App\Repositories\User\UserRepositoryInterface',
              'App\Repositories\User\UserRepository');

        // Binding another repository if has multiple repository
//         $this->app->bind(
//             'App\Repositories\PostRepositoryInterface',
//             'App\Repositories\PostRepository'
//         );

        //Another approach of binding repository
//           $this->app->bind(
//             CustomerRepositoryInterface::class,
//             CustomerRepository::class
//         );

    }
}

【问题讨论】:

  • 此上下文绑定不会影响您的应用程序或数据库。

标签: laravel repository-pattern


【解决方案1】:

您可以尝试注入具体的存储库而不是抽象/接口,容器将解析它们。

或者,您可以在服务提供者中使用“when/then”链:

$this->app->when(UserService::class)->needs(UserRepositoryInterface::class)->give(UserRepository::class);

您必须对服务提供商中需要 RepositoryInterface 的每个服务(或任何类)重复此操作。它的作用是在需要抽象时为特定类绑定一个具体化,这就是为什么您需要为每个需要您的接口的类执行相同的绑定。

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2011-07-31
    • 2020-09-22
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多