R
R
rumasterov2016-10-15 21:20:18
PHP
rumasterov, 2016-10-15 21:20:18

Faced with Circular Dependency, how to properly design a layer for working with an external data source (REST API)?

Hello.
There is a REST API for which you need to write a small client. I decided to do it this way:
There are UserMapper and PostMapper classes.
The UserMapper class has the getUserWithPosts($userId) method, the PostMapper class has the getPostWithUser($postId) and getPostListByUserId($userId) methods.
Inside the getUserWithPosts($userId) method of the UserMapper class, I send a request to the api where I query the user by id and fill in the User model with data, after which I call PostMapper inside the UserMapper and its getPostListByUserId($userId) method where the api request is made and the user's posts are requested, after which I map the Post model and add it to the PostCollection object and write a link to this collection in User.
The problem is the following, I started using Dependency Injection Container with dependency injection through the constructor. And then the following happened: my UserMapper depends on PostMapper (inside the getUserWithPosts($userId) method, PostMapper is called and posts are loaded) and PostMapper depends on UserMapper (inside the getPostWithUser() method, a post is loaded and the user is loaded through UserMapper).
Thus, a Circular Dependency error occurs, dependencies cannot be resolved because they point to each other.
Advise someone how to resolve the domain model when the source is not a database, but a REST API? Of course, you can not call another mapper inside the mapper method, but duplicate the logic from another mapper, then of course there will be no such error, but I don’t like that the logic will be duplicated.
There was also an idea to create a UserService, where there will be a getUserWithPosts method and call two mappers inside this method, then they will not depend on each other. But I don't know how correct it is.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question