I was doing some refactors to an API that I’m building and stumbled across a bucket of duplication.
Note:I’m going to abstract away a lot of the domain for the examples.
I happen to be using explicit route model binding, figured I should share that for some context:
So here is where I was finding heaps of duplication…
This pattern was repeated in several controllers. So what I ended up doing was extracting the configuration into a middleware.
In order for this to work, I needed to ensure that the IOC Container had the Gateway service bound as a singleton so it would always resolve the same instance every time its requested.
Then I was able to refactor all my controllers.
This feels a lot cleaner to me, now the controllers are really only concerned with the specific details necessary for handling the request.