4. Dependency injection

Dependency Injection is ...TODO ...

Dependency Injection in the framework is based on string based object naming, namespaced with dots. You can split your application in as many namespaces as you want, this gives you all the flexibility you can need to properly partition the application code. Configuration is based on XML. At the base level, there is a Container for each namespace you define in the application. Each Container can build all the objects of his namespace, and has some utility methods to retrieve objects by types (class or interface).

An example is better than 100 words, so let’s show you a basic example where we configure 4 imaginary User objects: the father John, his wife Mary, and their children Michael and Anne.

<objects>
	<object id=”John” class=”User”>
		<properties>
			<property name="name" type="string">John</property>
			<property name="surname" type="string">Brown</property>
			<property name="age" type="integer">42</property>
			<property name="wife" type="object">Mary</property>
			<property name=”children” type=”array”>
				<item key=”Michael” type=”object”>Michael</item>
				<item key=”Anne” type=”object”>Anne</item>
			</property>
		</properties>
	</object>
	<object id=”Mary” class=”User”>
		<properties>
			<property name="name" type="string">Mary</property>
			<property name="surname" type="string">Brown</property>
			...
		</properties>
	</object>
	<object id=”Michael” class=”User”>
		...
	</object>
	<object id=”Anne” class=”User”>
		...
	</object>
</objects>

All 4 objects are declared to be of class User, that we can easily implement as:

<?php
class User {
	protected $name;
	protected $surname;
	protected $age;
	protected $children = [ ];

	function __get($k) {
		return $this->$k;
	}
}

Now we can ask the Container to retrieve the object “John”:

<?php
use metadigit/core/depinjection/Container;
include ‘index.php’;
$Container = new Container(‘myproject’, ’/var/www/myproject.com/private/myproject/container.xml’);
John = $Container->get(‘John’);
echo $John->name; // prints “John”
echo $John->age; // prints “42”
foreach($John->children as $Child) {
	echo $Child->name . ‘: ‘ . $Child->age; // prints “Michael: 13” and “Anne: 8”
}

Please note how we iterate on John children, without explicitly retrieve them from the Container. Inside the configuration of John we declared the children array as reference to the other 2 objects Michael and Anne: the Container automatically (and lazily) will instantiate the 2 children objects when used inside the foreach cycle.