Migrating Slim from 2 to 3

One of the main structural differences in switching from V2 to V3 of the Slim framework is the action method signature. In slim 2 it was just simple, there was nothing except the route parameters passed into the callable, whether it was a Closure or a controller. This provided a super easy API to write complex controllers.

Let's bring the simplicity back

In some of my larger projects, I have controllers filled with actions, and there is so much noise from the action method signature. It really is tiresome to look at. It made me think, what the hell why can't I have simplicity and clean controllers back. Slim supports custom Invocable strategies, so I went to work on building one that would make me happy looking at my code. Readability is really important to me, and if you agree I think you will like this composer package.


Setter Injection Strategy

Since most of my code is built in Controllers, I immediately went to setter injection as the solution. I know from the work flow of the slim internals that construction injection would be a huge pain to implement and that setters were the way to go. The reason constructor injection will not work is because the callable needs to be resolved before the invocation of the strategy. The Slim internals would need to be rewritten to do this, and while it would be cleaner, it would also require a new version release. Perhaps something for 4.0.

The idea of this package is to inject the Request, Response into the controller, since in typical scenarios one controller action is mapped to one request. This frees up the method signature and turns it back into a Slim 2 style. All of this is done via the SetterInjectionStrategy interface which has 2 set methods to implement one for the Request object generated by your middleware and one for the Response object.

Return of Slim 2 style

class abcController implements SetterInjectionReceiver {
  //.. Implement and store the Objects somewhere up here.
  public function myAction ($arg1, $arg2, $arg3) {
    //..  This is now much more Slim 2 style

I hope you all find this package helpful. If you have any problems please do create an issue on the repo :)

Written by Glenn Eggleton on Friday March 4, 2016
Permalink - Chapter: Slim