[英]Laravel: How to implement Repository Design Pattern with only one repository?
我检查了许多存储库设计模式教程,例如
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-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;
}
}
在 RepositoryServiceProvider 中:
$this->app->bind(
'App\Repositories\PostRepositoryInterface',
'App\Repositories\PostRepository'
);
所以现在我有UserRepository
, PostRepository
, CommentRepository
.... 等我必须在所有存储库中添加相同的get
, add
, .... 方法,只需将模型名称从Post
更改为User
.... 等
如何将这些方法统一在一个文件中,只传递模型名称并像这样使用它$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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.