I am trying to create a clean service level in which the service level acts on one or more repositories, and each repository operates on its own eloquent model.
For example, I might have:
ForumService | +-- PostRepo extends PostInterface | | | +-- Post (Eloquent) | +-- UserRepo extends UserInterface | +-- User (Eloquent)
Each service defines the necessary dependencies through ioc . So something like:
// MessageService // .. public function __construct(UserInterface $userRepository, MessageInterface $messageRepository) { // .. }
My repositories are resolved through their bindings in their respective service providers, such as:
class UserRepositoryServiceProvider extends ServiceProvider { public function register() { $this->app>bind( 'App\Models\Repositories\User\UserInterface', 'App\Models\Repositories\User\UserRepository'); } }
It all works great. Each service receives the required repositories.
To maintain a level of service without any particular dependence on eloquence, everything that a repo leaves is a simple, immutable data object.
Key points in everyday language:
- Only repos communicate with their own models directly
- Repo returns simple, immutable data objects
- Services act to link multiple repos together and present simplified objects back to controllers and, ultimately, views.
However, I canβt come up with a clean template for associate eloquent models to each other at the service or repo level.
Given that the Post model has a belongsTo(User::class) relation, how can I cleanly create this relation at the Post repository level.
I tried:
public function associate($authorId) { $post->author()->associate($authorId); }
But associate expects a user eloquent object, not just an identifier. I could do:
public function associate($authorId) { $post->from()->associate($userRepo->findEloquent($authorId)); }
But I feel that I am popping up an eloquent model in a repo that should not act on it.
eloquent repository-pattern laravel service-layer
Chris
source share