Understand the driving concepts and reasons for using Dependency Injection
Understand the pattern and its usages in Drupal 8 specifically, via the Service Container and specific methods
implements
INVERSION
OF CONTROL
DEPENDENCY INJECTION
is a
DESIGN
PATTERN
enables
LOOSE
COUPLING
Reusable solution for common software design problems.
Examples:
Less
interconnection
Less
knowledge about each other
Less
coordination
is a PRINCIPLE,
which offers
Example of tight coupling
Example of tight coupling
Example of less tight coupling
Example of tight coupling
Example of less tight coupling
Loose Coupling
Who is responsible for instantiating the Notifier class?
VS.
describes a design in which a re-usable library calls the custom code and not the other way around
Drupal 7
The hook system
Drupal 8
Event Listener/
Observer pattern
implements
INVERSION
OF CONTROL
DEPENDENCY INJECTION
is a
DESIGN
PATTERN
enables
LOOSE
COUPLING
"When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might even be looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat."
John Munsch, 28 October 2009.
D8 Service Container
public static function create()
services:
http_kernel:
class: Stack\StackedHttpKernel
http_kernel.basic:
class: Symfony\Component\HttpKernel\HttpKernel
arguments: ['@event_dispatcher', '@controller_resolver', '@request_stack']
Example
services:
module_name.notifier:
class: Drupal\module_name\Notifier
arguments: ['']
Example
Creates an instance of the service with all the necessary dependencies by calling the Container::createService method.
public function getInstanceFromDefinition($definition) {
if ($this->container->has($definition)) {
$instance = $this->container->get($definition);
}
else {
if (!class_exists($definition)) {
throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $definition));
}
if (is_subclass_of($definition, 'Drupal\Core\DependencyInjection\ContainerInjectionInterface')) {
$instance = $definition::create($this->container);
}
else {
$instance = new $definition();
}
}
if ($instance instanceof ContainerAwareInterface) {
$instance->setContainer($this->container);
}
return $instance;
}