laravel - How to decouple eloquent from the service layer? -
i attempting create clean cut service layer, whereby service layer acts upon 1 or more repositories, , each repositories acts on own eloquent model.
for example, may have:
forumservice | +-- postrepo extends postinterface | | | +-- post (eloquent) | +-- userrepo extends userinterface | +-- user (eloquent) each service defines it's required dependencies via ioc. so, like:
// messageservice // .. public function __construct(userinterface $userrepository, messageinterface $messagerepository) { // .. } my repositories resolved via bindings in 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'); } } this works fine. each service gets repositories requires.
to keep service layer clear of specific dependency on eloquent, leaves repo simple, immutable, data object.
key points in everyday language:
- only repo's talk own models directly
- repo's return simple, immutable, data objects
- services act tie multiple repo's , present simplified objects controllers, , views.
however can't come clean pattern associate eloquent models each other @ service or repo layer.
given post model has belongsto(user::class) relationship, how cleanly create relationship @ post repository layer.
i have tried:
public function associate($authorid) { $post->author()->associate($authorid); } but associate expects user eloquent object, not id. do:
public function associate($authorid) { $post->from()->associate($userrepo->findeloquent($authorid)); } but feel surfacing eloquent model repo shouldn't acting on it.
the easy way:
public function assigntoauthor($postid, $authorid) { $post = $this->find($postid); // or whatever method use find id $post->author_id = $authorid; } now, above implies know foreign key author_id of relation. in order abstract bit, use this:
public function assigntoauthor($postid, $authorid) { $post = $this->find($postid); $foreignkey = $post->author()->getforeignkey(); $post->{$foreignkey} = $authorid; } mind, still need save $post model, suppose know that.
depending on implementation of simple, immutable, data object use, allow passing objects instead of raw ids. between lines:
public function assigntoauthor($postid, $authorid) { if ($postid instanceof yourdataoject) { $postid = $postid->getid(); } if ($authorid instanceof yourdataoject) { $authorid = $authorid->getid(); } // ... }
Comments
Post a Comment