我正在尝试创建一个干净的服务层,其中服务层作用于一个或多个存储库,并且每个存储库都在其自己的雄辩模型上运行。如何从服务层分离雄辩?
例如,我可以具有:
ForumService
|
+-- PostRepo extends PostInterface
| |
| +-- Post (Eloquent)
|
+-- UserRepo extends UserInterface
|
+-- User (Eloquent)
每个服务定义它经由ioc
需要的依赖。所以,像这样:
// MessageService
// ..
public function __construct(UserInterface $userRepository,
MessageInterface $messageRepository) {
// ..
}
我的仓库通过其绑定在各自的服务供应商解决,如:
class UserRepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app>bind(
'App\Models\Repositories\User\UserInterface',
'App\Models\Repositories\User\UserRepository');
}
}
这一切工作就好了。每个服务都可以获得它需要的存储库。
为了使服务层不受任何依赖于雄辩的影响,任何留下回购的东西都是一个简单的,不可变的数据对象。
在日常语言要点:
- 只有回购的谈话,以自己的模式直接
- 回购回归简单的,一成不变的,数据对象
- 服务行动,以配合多种回购的一起和现在简化的对象返回到控制器,最终还是视图。
然而我不能想出的服务或回购层干净的模式associate
雄辩模型给对方。
鉴于Post
模型具有belongsTo(User::class)
关系,我如何在Post
存储库层干净地创建该关系。
我曾尝试:
public function associate($authorId)
{
$post->author()->associate($authorId);
}
但associate
期望一个user
雄辩的对象,而不仅仅是一个ID。我可以这样做:
public function associate($authorId)
{
$post->from()->associate($userRepo->findEloquent($authorId));
}
但我觉得我正在浮出水面模型,进入一个不应该作用于其上的回购。
那么您还有什么问题吗?或者答案是你问的? –