Skip to content
Greg Bowler edited this page Nov 30, 2023 · 3 revisions

The PHP.Gt/ServiceContainer is a library to handle automatic dependency injection within your projects, and is used to automatically provide parameters to go and do functions within WebEngine projects.

The Container class is used to instantiate the objects your project is dependent on in an efficient way.

The Injector class is used to provide the objects from the Container to functions of your application, according to the functions' parameter types.

This technique allows you to move the "plumbing" of your project away from the main logic functions. For example, below is an index.php of a WebEngine application, where the entry point go function is automatically provided all the objects that are requested in the function parameters. Note that the developer can change the order of the parameters, drop parameters, or introduce new parameters to the go function, and the Service Container will automatically inject the correct objects without any need to reconfigure.

index.php:

<?php
function go(HTMLDocument $document, Database $db):void {
	$ul = $document->querySelector("ul");

	foreach($db->fetchAll("example/getAll") as $row) {
		$li = $document->createElement("li");
		$li->textContent = $row->getString("name");
		$ul->appendChild($li);
	}
}

In the next section, learn more about the Container class.

Clone this wiki locally