Laravel 6 中需在 AppServiceProvider@register() 中用 $this->app->bind() 绑定 PostRepositoryInterface 到 EloquentPostRepository,控制器类型提示接口即可自动注入,Repository 仅负责数据访问,不处理业务逻辑,返回 Eloquent 实例以保留扩展能力。

在 Laravel 6 中,服务容器绑定仓库接口是实现仓储模式(Repository Pattern)解耦的关键一步。核心不是“写个类就行”,而是让容器知道:当某处类型提示了 PostRepositoryInterface,就该自动注入 EloquentPostRepository 的实例。
接口与实现类要先建好
按约定组织目录:
- 在
app/Repositories/Interfaces/下创建PostRepositoryInterface.php,只声明方法(如find($id)、published()) - 在
app/Repositories/下创建EloquentPostRepository.php,实现该接口,内部使用Post::query()等 Eloquent 操作 - 确保两个类都正确声明命名空间,比如
App\Repositories\Interfaces和App\Repositories
绑定必须在服务提供者中完成
推荐在 AppServiceProvider@register() 方法里写绑定逻辑:
- 用
$this->app->bind(PostRepositoryInterface::class, EloquentPostRepository::class); - 不要用
app()->bind()全局函数,避免测试时容器状态污染 - 如果实现类构造函数需要依赖(如
Cache或Logger),Laravel 会自动解析——前提是它们本身也已注册到容器
控制器里只面向接口写依赖
Controller 构造函数直接类型提示接口,不 new、不 app()->make():
public function __construct(PostRepositoryInterface $posts) { $this->posts = $posts; }- 后续方法中调用
$this->posts->published()即可,完全不知道背后是 Eloquent 还是 API 或 Mock - 单元测试时,只需在测试中 bind 一个 Mock 实现,控制器逻辑无需改动
别踩这些常见坑
实战中容易忽略但影响长期维护的细节:
- Repository 不处理业务规则:比如“发布前检查作者权限”应放在 Service 层,Repository 只管“怎么查出已发布的文章”
- 简单单表操作(
Post::find(1)、Post::all())没必要进 Repository,徒增抽象层 - 返回值保持 Eloquent Collection 或 Model 实例,别转成数组——否则丢失
->load()、->append()等能力 - 若需运行时参数(如租户 ID),不要塞进构造函数,改用方法参数或 setter 注入
不复杂但容易忽略。绑定只是起点,真正价值在于后续所有依赖它的代码都获得了可替换、可测试、可演进的基础。


















