【问题标题】:Laravel: How to implement Repository Design Pattern with only one repository?Laravel:如何仅使用一个存储库实现存储库设计模式?
【发布时间】:2021-07-18 12:53:58
【问题描述】:

我查看了许多存储库设计模式教程,例如

https://asperbrothers.com/blog/implement-repository-pattern-in-laravel/ https://www.larashout.com/how-to-use-repository-pattern-in-laravel https://laravelarticle.com/repository-design-pattern-in-laravel https://shishirthedev.medium.com/repository-design-pattern-in-laravel-application-f474798f53ec

但所有人都使用多个存储库,每个模型都重复所有方法,这是一个示例

class PostRepository implements PostRepositoryInterface
{
  public function get($post_id)
  {
    return Post::find($post_id);
  }

  public function all()
  {
    return Post::all();
  }
} 

interface PostRepositoryInterface
{
  public function get($post_id);

  public function all();
}

class PostController extends Controller
{

  protected $post;

  public function __construct(PostRepositoryInterface $post)
  {
    $this->post = $post;
  }

  public function index()
  {
    $data = [
        'posts' => $this->post->all()
    ];
    return $data;
  }
}

在 ReposiroryServiceProvider 中:

$this->app->bind(
    'App\Repositories\PostRepositoryInterface',
    'App\Repositories\PostRepository'
);

所以现在我有 UserRepositoryPostRepositoryCommentRepository .... 等我将不得不在所有存储库中添加相同的方法 getadd、....型号名称从PostUser ....等

我怎样才能将这些方法统一到一个文件中,只传递模型名称并像 $this->model->all() 这样使用它,而不是在我创建的每个存储库文件中重复它们?

【问题讨论】:

    标签: laravel repository-pattern


    【解决方案1】:

    你需要Abstract ClassAbstractRepository,类似这样的东西。

    顺便说一句,也许你不需要存储库模式,在 Laravel 中这不是最佳实践。

    abstract class AbstractRepository
    {
         private $model = null;
         //Model::class
         abstract public function model(): string
         protected function query()
         {
             if(!$this->model){
               $this->model = app($this->model());
             }
             return $this->model->newQuery()
         }
         public function all()
         {
            return $this->query()->all();
         }
    }
    

    【讨论】:

    • 您能描述一下如何实现它吗?您认为最好的做法是什么而不是使用存储库?非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    相关资源
    最近更新 更多