Posts RSS Comments RSS

What is Dependency Injection?

I’m a big fan of OOP, design patterns and good software design, so I try constantly to learn new things and prepare myself for being a good software architect. One of the hottest things I’ve learned about lately is the dependency Injection (DI) pattern.
Basically, DI is about getting from this:

$_SESSION['language'] = ‘fr’;
$user_language = $_SESSION['language'];

to this:

$sc = new sfServiceContainerBuilder(array(
’storage.class’ => ’sfMySQLSessionStorage’,
’storage.options’ => array(’database’ => ’session’, ‘db_table’ => ’session’),
‘user.class’ => ’sfUser’,
‘user.default_culture’ => ‘fr’,
));

$sc->register(’dispatcher’, ’sfEventDispatcher’);

$sc->
register(’storage’, ‘%storage.class%’)->
addArgument(’%storage.options%’)
;

$sc->
register(’user’, ‘%user.class%’)->
addArgument(new sfServiceReference(’dispatcher’))->
addArgument(new sfServiceReference(’storage’))->
addArgument(array(’default_culture’ => ‘%user.default_culture%’))->
;

$user = $sc->user;

The later is cleaner and better because it encourages the separation of concerns and other OOP best practices, and of course, it uses DI !

More about how to better engineer your code using Dependency Injection here: http://components.symfony-project.org/dependency-injection/documentation

Click here to find another method to write good code.


evolution-man-computer

Trackback this post | Feed on Comments to this post

Leave a Reply