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

Gonzalo Ayuso:
Alternative way to inject providers in a Silex application
Oct 19, 2015 @ 16:18:10

Gonazalo Ayuso has shared a method he's found for injecting providers into Silex that replaces accessing the dependency injection container as an array. It instead replaces it and allows defining function parameters instead.

I normally use Silex when I need to build one Backend. It’s simple and straightforward to build one API endpoint using this micro framework. But there’s something that I don’t like it: The “array access” way to access to the dependency injection container. I need to remember what kind of object provides my service provider and also my IDE doesn’t help me with autocompletion. OK I can use PHPDoc comments or even create one class that inherits from SilexApplication and use Traits. Normally I’m lazy to do it. Because of that I’ve create this simple service provider to help me to do what I’m looking for. Let me explain it a little bit.

He includes examples of both the normal way you can access Silex's injection containers (the "array access" method) and contrasts this with his updated method, via a method parameter on the route closure. His service provider (complete code in the post and on github), when registered, looks for controller events and performs reflection on the closure to detect which objects need to be injected. The method is then called normally but with the extra attributes set, populating the parameters.

tagged: slex service provider alternative array access parameter method dependency injection

Link: http://gonzalo123.com/2015/10/19/alternative-way-to-inject-providers-in-a-silex-application/


Trending Topics: