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

Zsolt Szend:
Dynamic dependency injection
May 18, 2016 @ 18:32:25

In this new tutorial Zsolt Szende talks about dependency injection and how to handle objects and related needs at runtime rather than the pre-configured method that some injection containers/systems have defined.

In this short article I would like to demonstrate a way to inject dependencies that are not known until runtime. There are many use cases for this and in essence it is about choosing between concrete implementations of some common interface. In object oriented design this is known at the Strategy pattern. The choice itself can be made in various ways, for example via a configuration option or a command line parameter in case of a console command, and I think the dynamic nature of the choice is the most interesting part of the pattern.

The article provides a practical example of an XML/JSON reader pulling information from an external source. A simple interface is defined and two implementation classes put it to use. Then the "command" pattern is used to apply it to an executable script and how injecting a reader type directly overrides the one from the provided option. This is taken a step further and refactored into a "resolver" to determine the best logic to apply based on the input argument.

tagged: dynamic dependency injection xml json reader tutorial resolver

Link: http://pwm.github.io/dynamic-dependency-injection/

Dave Marshall:
Silex Controllers as Services
Oct 03, 2012 @ 14:36:15

Dave Marshall has written up a post about how he uses Silex controllers as services that allow him to define his controller methods in separate classes with a custom resolver.

There’s currently a pull request in the queue for Silex that adds a cookbook entry for using controller classes, but I wanted to take it a step further and have my controllers as services, much like what’s possible with the full symfony framework (See Richard Miller’s post for further reading).

He includes some example code showing the creation of the Silex application with a service definition, the custom "ControllerResolver" to override the default and a simple controller class ("PostController") that just returns a JSON response. You can find the full example code for it on github.

tagged: silex controller service resolver class tutorial microframework

Link:


Trending Topics: