luddinus's avatar

Am I abstracting too much?

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?

0 likes
7 replies
cm's avatar

Looks like a pretty default abstraction to me.

How do you think? Am I too paranoid?

Pretty hard to judge what you want to hear. What would be "too paranoid" and for what?

luddinus's avatar

@cm

"Too paranoid" because, one of the main reasons. I don't think I'm going to switch Eloquent...

cm's avatar

So, the question isn't about removing Eloquent from your controllers, but removing Eloquent from all models.

Please read this thread. We talked about repositories and Eloquent in depth there. There is no simple answer to your question.

pobble's avatar

There is another huge benefit to repositories other than abstraction. Good method names signal intent in your controller rather than having to figure out what a long chained Eloquent query is doing. That and they keep your controllers nice and clean. Also while you may not intend to switch away Eloquent, don't chance it. The next greatest PHP db abstraction might be two months away!

xsmalbil@icloud.com's avatar

You should always want to abstract the database interactions to repositories. But the way you are moving, you should step away from active record and try doctrine with yaml annotations so that the orm annotation reader isn't coupled to your entities.

luddinus's avatar
luddinus
OP
Best Answer
Level 6

Well, I realize this was a good example of "premature" abstraction.

2 likes

Please or to participate in this conversation.