SlideShare a Scribd company logo
Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in
Drupal 8
Ashwini Kumar
Who am I?
Ashwini Kumar
Tech Architect
@ashclimb
Agenda
✤ Mystery about DI
✤ Why to give my 2 cents to learn DI?
✤ DI in Symfony
✤ DI in Drupal 8
What is Dependency Injection?
Well, the literal meaning is injecting the dependency into
your Class.
DI Ground zero
DI Ground zero
DI Ground zero
DI Ground zero
Types of Dependency Injection
✤ Constructor Injection
✤ Setter Injection
✤ Property Injection
Constructor Injection
class NewsletterManager {
protected $mailer;
public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}
// ...
}
Setter Injection
class NewsletterManager {
protected $mailer;
public function setMailer(Mailer $mailer) {
$this->mailer = $mailer;
}
// ...
}
Property Injection
class NewsletterManager {
public $mailer;
// ...
}
Why Dependency Injection?
Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLA
Without dependency injection
class GoogleMaps {
public function getCoordinatesFromAddress($address) {
// calls Google Maps webservice
}
}
class OpenStreetMap {
public function getCoordinatesFromAddress($address) {
// calls OpenStreetMap webservice
}
}
class StoreService {
public function getStoreCoordinates($store) {
$geolocationService = new GoogleMaps();
// or $geolocationService = GoogleMaps::getInstance() if you use singletons
return $geolocationService->getCoordinatesFromAddress($store->getAddress());
}
}
Without dependency injection
With dependency injectionclass StoreService {
private $geolocationService;
public function __construct(GeolocationService $geolocationService) {
$this->geolocationService = $geolocationService;
}
public function getStoreCoordinates($store) {
return $this->geolocationService->getCoordinatesFromAddress($store-
>getAddress());
}
}
With dependency injection
interface GeolocationService {
public function getCoordinatesFromAddress($address);
}
class GoogleMaps implements GeolocationService { ...
class OpenStreetMap implements GeolocationService { ...
What we also get from this…
✤ Cleaner and Modular
✤ Reusable and Flexible
✤ Abstraction
✤ Testable
DI in a Framework
Dependency Injector
==
Dependency Injection Container(DIC)
==
IoC Container
==
Service Container
er
What is Service Container?
It basically deals with creating a map of your dependencies
which your class needs and check do we have it loaded?
Symfony’s Dependency injection
component
Symfony’s DI Component
✤ Services Keys are strings, e.g.
‘some_service’
✤ Service definitions in addition to specifying
which class to instantiate and what
constructor arguments to pass in, allow you
to specify additional methods to call on the
object after instantiation.
Symfony’s DI Component
✤ Default scope: Container
✤ Can be configured in PHP, XML or YAML
✤ Can be “compiled” down to plain PHP
Dependency Injection in Drupal 8
D8 Services mostly we will be using
✤ The default DB connection (‘database’)
✤ The module handler (‘module handler’)
✤ The HTTP request object (‘request’)
2 ways you can use core’s
services
1. Service location : From procedural code,
using a helper:
Drupal::service(‘some_service’)
2. DI way : Write OO code and get wired
into the container
How and Where does it all happen?
✤ The Drupal Kernel: code/lib/Drupal/Core/DrupalKernel.php
✤ Services are defined in : core/core.services.yml
✤ Compiler passes get added in: core/lib/Drupal/Core/CoreBundle.php
✤ Compiler pass classes live here:
core/lib/Drupal/Core/DependenciesInjection/compiler/…
How does it happen for my Module?
✤ Services are defined in : mymodule/mymodule.services.yml
✤ Compiler passes get added in: my
module/lib/Drupal/mymodule/MymoduleBundle.php
✤ All classes, including compiler pass classes must live in : my
module/lib/Drupal/mymodule/
What Magic do we have in *.services.yml ?
services:
# Defines a simple service of which requires no parameter for its constructor.
example.simple:
class: DrupalExampleSimple
# Defines a service which requires the module_handler for its constructor.
example.with_module_handler
class: DrupalExampleWithModuleHandler
arguments: ['@module_handler']
Implement:Dependency Injection for a Form
https://api.drupal.org/api/drupal/services
“Start Small, then work your way up!”
~ The person who is quoted
Questions?
So How Was It? - Tell Us What You
Think
Evaluate this session - thisistheurltotheschedule
Thanks!

More Related Content

What's hot (20)

PPTX
Domain Driven Design using Laravel
wajrcs
 
PDF
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Javier Eguiluz
 
PPTX
Java script basic
Ravi Bhadauria
 
PPTX
Only oop
anitarooge
 
PDF
Design how your objects talk through mocking
Konstantin Kudryashov
 
PDF
Love and Loss: A Symfony Security Play
Kris Wallsmith
 
PDF
Angular Directives from Scratch
Christian Lilley
 
PDF
Modern JavaScript Programming
Wildan Maulana
 
PDF
How I started to love design patterns
Samuel ROZE
 
PDF
Design Patterns in PHP5
Wildan Maulana
 
ODP
Angularjs
Vincenzo Ferrari
 
DOCX
Dot Net Accenture
Sri K
 
PPTX
Javascript for the c# developer
Salvatore Fazio
 
PDF
Angular custom directives
Alexe Bogdan
 
PDF
A Gentle Introduction To Object Oriented Php
Michael Girouard
 
PDF
Advanced Interfaces and Repositories in Laravel
Jonathan Behr
 
PPTX
Object oriented php
jwperry
 
ODP
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
PPTX
JavaScript Literacy
David Jacobs
 
PPT
Oops concepts in php
CPD INDIA
 
Domain Driven Design using Laravel
wajrcs
 
New Symfony Tips & Tricks (SymfonyCon Paris 2015)
Javier Eguiluz
 
Java script basic
Ravi Bhadauria
 
Only oop
anitarooge
 
Design how your objects talk through mocking
Konstantin Kudryashov
 
Love and Loss: A Symfony Security Play
Kris Wallsmith
 
Angular Directives from Scratch
Christian Lilley
 
Modern JavaScript Programming
Wildan Maulana
 
How I started to love design patterns
Samuel ROZE
 
Design Patterns in PHP5
Wildan Maulana
 
Angularjs
Vincenzo Ferrari
 
Dot Net Accenture
Sri K
 
Javascript for the c# developer
Salvatore Fazio
 
Angular custom directives
Alexe Bogdan
 
A Gentle Introduction To Object Oriented Php
Michael Girouard
 
Advanced Interfaces and Repositories in Laravel
Jonathan Behr
 
Object oriented php
jwperry
 
Rich domain model with symfony 2.5 and doctrine 2.5
Leonardo Proietti
 
JavaScript Literacy
David Jacobs
 
Oops concepts in php
CPD INDIA
 

Similar to Dependency injection in Drupal 8 : DrupalCon NOLA (20)

PDF
Dependency injection Drupal Camp Wrocław 2014
Greg Szczotka
 
PDF
Leveraging the Command Pattern: Enhancing Drupal with Symfony Messenger.pdf
Luca Lusso
 
PDF
Symfony2 - from the trenches
Lukas Smith
 
ODP
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
PDF
Symfony2 from the Trenches
Jonathan Wage
 
PDF
Hexagonal architecture
Alessandro Minoccheri
 
PDF
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
ODP
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
PDF
The Naked Bundle - Tryout
Matthias Noback
 
PPTX
Neoito — Design patterns and depenedency injection
Neoito
 
PDF
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
PDF
Osiąganie mądrej architektury z Symfony2
3camp
 
PDF
Java Programming
Tracy Clark
 
PDF
Dependency Inversion and Dependency Injection in PHP
mtoppa
 
PDF
Write your first WordPress plugin
Anthony Montalbano
 
PDF
The Naked Bundle - Symfony Live London 2014
Matthias Noback
 
PPTX
Introduction to OO, Java and Eclipse/WebSphere
eLink Business Innovations
 
PDF
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Loz Calver
 
PDF
How to improve the quality of your TYPO3 extensions
Christian Trabold
 
Dependency injection Drupal Camp Wrocław 2014
Greg Szczotka
 
Leveraging the Command Pattern: Enhancing Drupal with Symfony Messenger.pdf
Luca Lusso
 
Symfony2 - from the trenches
Lukas Smith
 
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
Symfony2 from the Trenches
Jonathan Wage
 
Hexagonal architecture
Alessandro Minoccheri
 
OOPs Interview Questions PDF By ScholarHat
Scholarhat
 
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
The Naked Bundle - Tryout
Matthias Noback
 
Neoito — Design patterns and depenedency injection
Neoito
 
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Osiąganie mądrej architektury z Symfony2
3camp
 
Java Programming
Tracy Clark
 
Dependency Inversion and Dependency Injection in PHP
mtoppa
 
Write your first WordPress plugin
Anthony Montalbano
 
The Naked Bundle - Symfony Live London 2014
Matthias Noback
 
Introduction to OO, Java and Eclipse/WebSphere
eLink Business Innovations
 
Why you shouldn’t edit silver stripe core files (and how to do it anyway)
Loz Calver
 
How to improve the quality of your TYPO3 extensions
Christian Trabold
 
Ad

Recently uploaded (20)

PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Electrical Engineer operation Supervisor
ssaruntatapower143
 
PDF
smart lot access control system with eye
rasabzahra
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
Big Data and Data Science hype .pptx
SUNEEL37
 
PPTX
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
Zilliz Cloud Demo for performance and scale
Zilliz
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
Design Thinking basics for Engineers.pdf
CMR University
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Electrical Engineer operation Supervisor
ssaruntatapower143
 
smart lot access control system with eye
rasabzahra
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Big Data and Data Science hype .pptx
SUNEEL37
 
MATLAB : Introduction , Features , Display Windows, Syntax, Operators, Graph...
Amity University, Patna
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
DATA BASE MANAGEMENT AND RELATIONAL DATA
gomathisankariv2
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
Zilliz Cloud Demo for performance and scale
Zilliz
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Thermal runway and thermal stability.pptx
godow93766
 
Ad

Dependency injection in Drupal 8 : DrupalCon NOLA

  • 3. Who am I? Ashwini Kumar Tech Architect @ashclimb
  • 4. Agenda ✤ Mystery about DI ✤ Why to give my 2 cents to learn DI? ✤ DI in Symfony ✤ DI in Drupal 8
  • 5. What is Dependency Injection? Well, the literal meaning is injecting the dependency into your Class.
  • 10. Types of Dependency Injection ✤ Constructor Injection ✤ Setter Injection ✤ Property Injection
  • 11. Constructor Injection class NewsletterManager { protected $mailer; public function __construct(Mailer $mailer) { $this->mailer = $mailer; } // ... }
  • 12. Setter Injection class NewsletterManager { protected $mailer; public function setMailer(Mailer $mailer) { $this->mailer = $mailer; } // ... }
  • 13. Property Injection class NewsletterManager { public $mailer; // ... }
  • 18. Without dependency injection class GoogleMaps { public function getCoordinatesFromAddress($address) { // calls Google Maps webservice } } class OpenStreetMap { public function getCoordinatesFromAddress($address) { // calls OpenStreetMap webservice } }
  • 19. class StoreService { public function getStoreCoordinates($store) { $geolocationService = new GoogleMaps(); // or $geolocationService = GoogleMaps::getInstance() if you use singletons return $geolocationService->getCoordinatesFromAddress($store->getAddress()); } } Without dependency injection
  • 20. With dependency injectionclass StoreService { private $geolocationService; public function __construct(GeolocationService $geolocationService) { $this->geolocationService = $geolocationService; } public function getStoreCoordinates($store) { return $this->geolocationService->getCoordinatesFromAddress($store- >getAddress()); } }
  • 21. With dependency injection interface GeolocationService { public function getCoordinatesFromAddress($address); } class GoogleMaps implements GeolocationService { ... class OpenStreetMap implements GeolocationService { ...
  • 22. What we also get from this… ✤ Cleaner and Modular ✤ Reusable and Flexible ✤ Abstraction ✤ Testable
  • 23. DI in a Framework Dependency Injector == Dependency Injection Container(DIC) == IoC Container == Service Container er
  • 24. What is Service Container? It basically deals with creating a map of your dependencies which your class needs and check do we have it loaded?
  • 26. Symfony’s DI Component ✤ Services Keys are strings, e.g. ‘some_service’ ✤ Service definitions in addition to specifying which class to instantiate and what constructor arguments to pass in, allow you to specify additional methods to call on the object after instantiation.
  • 27. Symfony’s DI Component ✤ Default scope: Container ✤ Can be configured in PHP, XML or YAML ✤ Can be “compiled” down to plain PHP
  • 29. D8 Services mostly we will be using ✤ The default DB connection (‘database’) ✤ The module handler (‘module handler’) ✤ The HTTP request object (‘request’)
  • 30. 2 ways you can use core’s services 1. Service location : From procedural code, using a helper: Drupal::service(‘some_service’) 2. DI way : Write OO code and get wired into the container
  • 31. How and Where does it all happen? ✤ The Drupal Kernel: code/lib/Drupal/Core/DrupalKernel.php ✤ Services are defined in : core/core.services.yml ✤ Compiler passes get added in: core/lib/Drupal/Core/CoreBundle.php ✤ Compiler pass classes live here: core/lib/Drupal/Core/DependenciesInjection/compiler/…
  • 32. How does it happen for my Module? ✤ Services are defined in : mymodule/mymodule.services.yml ✤ Compiler passes get added in: my module/lib/Drupal/mymodule/MymoduleBundle.php ✤ All classes, including compiler pass classes must live in : my module/lib/Drupal/mymodule/
  • 33. What Magic do we have in *.services.yml ? services: # Defines a simple service of which requires no parameter for its constructor. example.simple: class: DrupalExampleSimple # Defines a service which requires the module_handler for its constructor. example.with_module_handler class: DrupalExampleWithModuleHandler arguments: ['@module_handler']
  • 36. “Start Small, then work your way up!” ~ The person who is quoted
  • 38. So How Was It? - Tell Us What You Think Evaluate this session - thisistheurltotheschedule Thanks!