Controllers, Services, Repositories and Models ... am I doing it right?

In most of my web applications I have the following 4 directories:

  • Controllers
  • Services
  • Repositories
  • Models

Over the years I’ve been trying to develop as “clean” as possible. I’ve read numerous books and articles. I seemed to have developed a way to keep things neat and tidy, but sometimes it feels like overkill.

It goes something like this:

  1. Everything starts at the controller. A request comes in. For example, a request to follow a user. I will have a FollowController. The FollowController has a FollowService dependency.
  2. The FollowController will do any validation checking on the inputs
  3. I then have a FollowService which has follow/unfollow methods. This service has a FollowRepository, and UserService dependency. In the FollowService follow method usernames are converted to ID’s, checks if the user exists, and then makes a call to FollowRepository::follow
  4. FollowRepository::follow will follow the user and make calls to the FollowModel.

In my mind I have the following rules:

  • A controller doesn’t make calls to a repository, or a model directly. Only to services
  • Services do not make calls directly to models, only repositories or other services
  • Repositories only call require models. If possible I try to ensure that each repo is attached to a single model.

At times there’s exceptions to this, in cases when making things overly complex isn’t required.

I just wanted to know if what I’m doing is correct, or whether I’m setting myself up for further issues. I don’t know if what I’m doing has a specific name, or if it’s a known methodology. It’s something I’ve picked up after a long time using Slim.

@JamesTheHacker I pretty much follow the same pattern, minus the repositories. My controllers only handle a route request and the controllers call methods on a service injected into the controller. The service can either make a direct query or make a request to an api and return the results. I usually let me controller handle the results to determine the message output to the view.

I used to add repositories for a bit but they were overkill and really are only meant to store data rather than be another service.

Regardless, the ‘clean’ development process is the way to go.

1 Like

1 You should inject only interfaces ( for repositories in this example)
2 Repositories with static method? i don’t like it :smiley: better an object


I usually inject the Entity into the repository, Example

$user = new User(“name”, “surname”);

I don’t actually use static methods. It’s something I use to show a method on a class. Apologies for the confusion.

@robrothedev I am starting to think the same way with repositories. Most times they are very much overkill. Thank you for your input :slight_smile: