I was prompted to write this post after seeing a couple of things pop up in my timeline.
Service locators don’t belong in controllers - https://t.co/XrtxBTlbtp— Brandon Savage (@brandonsavage) June 1, 2016
Brandon's article carries an overarching message and he states it in his rule of thumb:
Service locators don’t belong inside controllers. Period.
I couldn't disagree more. Controllers are the number one place I use a service locator and it seems I'm not the only one, as hinted at by Konstantin, also tweeting today:
I spent way too much time in the past making controllers "clean". Nowadays they'd re dirty as sin...— Konstantin K (@everzet) May 31, 2016
I used to think like Brandon. I used to try and keep my controllers clean too, but like Konstantin, at some point a few years ago I realised I didn't need to anymore. I was getting better at putting clean clode in the proper places and as Konstantin puts it, I could make my controllers as dirty as sin.
I've come full circle on controllers. I was isolating them from the framework. Now I don't care, couple them as tightly as I like.— Dave Marshall (@davedevelopment) April 30, 2014
In a typical MVC framework, controllers are for converting a HTTP request in to something suitable to send to your actual application code. The better you get at extracting business logic or even just complicated HTTP layer logic to places outside your controllers, the thinner and dumber your controllers get. Once they get dumb and thin, it makes sense to leverage the conveniences that a decent MVC framework provides for you.
If I'm making changes to a controller and it starts to get painful, there's a good chance I would look to extract some logic out of the controller, rather than extracting the conveniences afforded me by the framework. This usually manifests in some sort of Service Layer for things coming in, and as Presenters for things going out.
Use and abuse your chosen framework, that's what it's there for.