Laravel:如何在只有一个存储库的情况下实现存储库设计模式



我看过很多像这样的存储库设计模式教程

https://asperbrothers.com/blog/implement-repository-pattern-in-laravel/https://www.larashout.com/how-to-use-repository-pattern-in-laravelhttps://laravelarticle.com/repository-design-pattern-in-laravelhttps://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;
}
}

在回购服务提供商中:

$this->app->bind(
'AppRepositoriesPostRepositoryInterface',
'AppRepositoriesPostRepository'
);

现在我有了UserRepositoryPostRepositoryCommentRepository。。。。等等,我将不得不添加与getadd、…相同的方法。。。。在所有存储库中,只需将模型名称从Post更改为User。。。。etc

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

您需要抽象类AbstractRepository,类似这样的东西。

顺便说一句,也许您不需要存储库模式,在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();
}
}

最新更新