Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Rob Allen:
DI Factories for Slim controllers
Apr 28, 2016 @ 15:38:10

In a recent post to his site Rob Allen shows you how to create dependency injection factories for Slim (v3) controllers.

When using classes for route actions in Slim 3, I recommend using a single class for each route. However you can use a single class for multiple routes. To register a class method to a route you pass a string as the route callable where the class name is separate from method by a colon. Slim will retrieve MyController from the DI container and then call the listAction method using the usual signature. f you don't specify a method, then Slim will see if it treat the class as a callable, so you can implement __invoke() and then register the route.

He shows how to create a factory method as a part of the Slim container for a constructor and inject the correct dependencies. He shows how to register these dependencies as other factory methods inside the DI container and how to pull them back out for injection. He prefers this method as it reduces "hidden dependency" issues and makes the controllers themselves easier to test.

tagged: slim3 slimframework dependency injection container tutorial factory

Link: https://akrabat.com/di-factories-for-slim-controllers/


Trending Topics: