【发布时间】: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'
);
所以现在我有 UserRepository、PostRepository、CommentRepository .... 等我将不得不在所有存储库中添加相同的方法 get、add、....型号名称从Post 到User ....等
我怎样才能将这些方法统一到一个文件中,只传递模型名称并像 $this->model->all() 这样使用它,而不是在我创建的每个存储库文件中重复它们?
【问题讨论】:
标签: laravel repository-pattern