Am I abstracting too much?

Posted 4 years ago by luddinus

I want to abstract Eloquent from my controllers completely. This is what I'm doing:

abstract class EloquentRepository implements RepositoryInterface {
    protected $query;

    public function __construct()
    {
          // child class must be named as "UserRepository"
          $child_name = str_replace('Repository', '', class_basename($this));
          $this->query = app($child_name)->newQuery();
    }

    public function getAll()
    {
         // makeEntityCollection maps each Eloquent record to an Entity
         return $this->makeEntityCollection($this->query->all());
    }

    public function getById($id)
    {
         return $this->makeEntity($this->query->findOrFail($id));
    }
}

Example of retrieving User's posts

class EloquentPostRepository extends BaseRepository {
     public function getPostsOfUser($user_id)
     {
           $collection = $this->query->with('user')->whereUserId($user_id)->get();

           return $this->makeEntityCollection($collection);
     }
}

class UserController {
     
     // Show 
     public function posts($user_id)
     {
          // injectedRepository
          $posts = $this->postRepository->getPostsOfUser($user_id);

          return view('user.posts', compact('posts'));
     }

}

Entities are PHP Plain Objects.

How do you think? Am I too paranoid?

Please sign in or create an account to participate in this conversation.