Posts tagged: xml

Quick Start Symfony DI (Dependency Injection) Tutorial

By , Saturday 14th August 2010 2:21 pm

What is Dependency Injection (DI)?

Dependency injection is a technique that allows for loosely coupled objects within a software application. Generally if an object requires access to the functionality of another it would be instantiated internally leading to tightly coupled systems. By implementing dependency injection we inject the required objects ready for use (sometimes also referred to inversion of control – IOC). Take the following example:

<?php
class DecisionMaker {
    public function makeDecision(array $parameters) {
        // Need the database adapter
        $dp = new DecisionParameters();
        $parameterScore = $dp->getScore($parameters);
        /* ... Some more decision logic ... */
        return ($parameterScore > 50);
    }
}

This piece of code is said to be tightly coupled to the DecisionParameters object. Rewriting the above in a loosely coupled fashion we’d have something like….

<?php
class DecisionMaker {
    private $_dp;
    public function __construct($dp) {
        $this->_dp = $dp;
    }
    public function makeDecision(array $parameters) {
        $parameterScore = $this->_dp->getScore($parameters);
        /* ... Some more decision logic ... */
        return ($parameterScore > 50);
    }
}

Whilst gaining the benefits of loosely coupled code we are adding complexity such that each time an object is instantiated we also have to instantiate its dependencies and pass these in too. For example, this:

$choice = new DecisionMaker();
echo $choice->makeDecision(array('effort' => 'low', 'return' => 'high'));

now becomes:

$dp = new DecisionParameters();
$choice = new DecisionMaker($dp);
echo $choice->makeDecision(array('effort' => 'low', 'return' => 'high'));

This situation becomes more painful as the number of dependencies for a class is increased, and what if the dependencies themselves have dependencies? This can quite quickly become an object administration nightmare! Enter dependency injection containers (or frameworks)…
Continue reading 'Quick Start Symfony DI (Dependency Injection) Tutorial'»

Panorama Theme by Themocracy

4 visitors online now
2 guests, 2 bots, 0 members
Max visitors today: 5 at 06:43 am UTC
This month: 14 at 11-05-2017 07:08 pm UTC
This year: 45 at 02-01-2017 10:28 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC