SlideShare a Scribd company logo
1 of 13
Download to read offline
Services, Dependency
Injection and Containers
In Drupal 8
About Me
Sushil Hanwate
Twitter: @thesushyl
Drupal Developer @
What is a Service?
A Service is any PHP object that performs some sort of "global" task.
It's a purposefully-generic name used in computer science to describe an
object that's created for a specific purpose (e.g. delivering emails).
As a rule, a PHP object is a service if it is used globally in your application.
Defining Services
// user.services.yml
services:
access_check.permission:
class: DrupaluserAccessPermissionAccessCheck // ‘modules/user/src/access/PermissionAccessCheck.php’
tags:
- { name: access_check, applies_to: _permission }
// core.services.yml
services:
path.alias_manager:
class: DrupalCorePathAliasManager // ‘/core/lib/drupal/core/path/AliasManager.php’
arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data']
Obtaining Services
Service Location (Procedural)
Dependency Injection (Used in classes)
Obtaining Services: Service Location
// Get service from outside of a class.
$service = Drupal::service('service_name');
// If you have $container variable
$service = $container->get('service_name');
// Example services
$cache = Drupal::cache();
$lock = Drupal::lock()->acquire($lock_name)
Obtaining Services: Service Location
// Source
$cache = Drupal::cache();
Dependency Injection - Definition
Dependency injection is a software design pattern in which
one or more dependencies/services are injected, or passed by
reference , into a dependent object/client and are made part
of the client's state.
The pattern separates the creation of a client's dependencies
from its own behavior, which allows program designs to be
loosely coupled and to follow the dependency inversion and
single responsibility principles.
Obtaining Services: Dependency Injection
1. DI is used in classes.
2. If your class is a service, inject dependencies via arguments in *.services.yml
services:
path.alias_manager:
class: DrupalCorePathAliasManager // ‘/core/lib/drupal/core/path/AliasManager.php’
arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data']
// code
public function __construct (AliasStorageInterface $storage,
AliasWhitelistInterface $whitelist,
LanguageManagerInterface $language_manager,
CacheBackendInterface $cache) {
Overriding Services
1. Locate default class and interface
2. Define a class that provides same services with different way implementing interface
and/or overriding the class, say
Drupalfoo_barMyNewServiceClass
1. Define a class that implements DrupalCoreDependencyInjectionServiceModifierInterface called
Drupalfoo_barFooBarServiceProvider
2. Put this in alter() method
public function alter(ContainerBuilder $container) {
$definition = $container->getDefinition('service.name');
$definition->setClass(Drupalfoo_barMyNewServiceClass);
}
Why Dependency Injection?
Clutter-free
Re-usable
Testable
References
1.http://www.slideshare.net/katbailey/di-drupal8
2.https://www.youtube.com/watch?v=TAXgizY-p4k
3.https://docs.acquia.com/articles/drupal-8-dependency-
injection
Questions?

More Related Content

Viewers also liked

Drupal and Devops , the Survey Results
Drupal and Devops , the Survey ResultsDrupal and Devops , the Survey Results
Drupal and Devops , the Survey ResultsKris Buytaert
 
Workflow Initiative
Workflow InitiativeWorkflow Initiative
Workflow Initiativetimmillwood
 
Hack Proof Your Drupal Site
Hack Proof Your Drupal SiteHack Proof Your Drupal Site
Hack Proof Your Drupal SiteNaveen Valecha
 
Show, Don't Tell: Online Storytelling through Digital Media
Show, Don't Tell: Online Storytelling through Digital MediaShow, Don't Tell: Online Storytelling through Digital Media
Show, Don't Tell: Online Storytelling through Digital Mediaffnatania
 
Continuous Integration & Drupal
Continuous Integration & DrupalContinuous Integration & Drupal
Continuous Integration & DrupalLimoenGroen
 
Grok Drupal (7) Theming
Grok Drupal (7) ThemingGrok Drupal (7) Theming
Grok Drupal (7) ThemingPINGV
 
D7 theming what's new - London
D7 theming what's new - LondonD7 theming what's new - London
D7 theming what's new - LondonMarek Sotak
 
Fundraising with Drupal
Fundraising with DrupalFundraising with Drupal
Fundraising with DrupalLev Tsypin
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 

Viewers also liked (11)

Drupal and Devops , the Survey Results
Drupal and Devops , the Survey ResultsDrupal and Devops , the Survey Results
Drupal and Devops , the Survey Results
 
Workflow Initiative
Workflow InitiativeWorkflow Initiative
Workflow Initiative
 
Hack Proof Your Drupal Site
Hack Proof Your Drupal SiteHack Proof Your Drupal Site
Hack Proof Your Drupal Site
 
Show, Don't Tell: Online Storytelling through Digital Media
Show, Don't Tell: Online Storytelling through Digital MediaShow, Don't Tell: Online Storytelling through Digital Media
Show, Don't Tell: Online Storytelling through Digital Media
 
Continuous Integration & Drupal
Continuous Integration & DrupalContinuous Integration & Drupal
Continuous Integration & Drupal
 
Message Queues and Drupal
Message Queues and DrupalMessage Queues and Drupal
Message Queues and Drupal
 
Grok Drupal (7) Theming
Grok Drupal (7) ThemingGrok Drupal (7) Theming
Grok Drupal (7) Theming
 
D7 theming what's new - London
D7 theming what's new - LondonD7 theming what's new - London
D7 theming what's new - London
 
Fundraising with Drupal
Fundraising with DrupalFundraising with Drupal
Fundraising with Drupal
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 

Similar to Services, dependency injection and containers

Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphonyBrahampal Singh
 
Symfony and Drupal 8
Symfony and Drupal 8Symfony and Drupal 8
Symfony and Drupal 8Kunal Kursija
 
Drupal 8 Vocabulary Lesson
Drupal 8 Vocabulary LessonDrupal 8 Vocabulary Lesson
Drupal 8 Vocabulary LessonMediacurrent
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in phpSHIVANI SONI
 
Services in Drupal 8
Services in Drupal 8Services in Drupal 8
Services in Drupal 8Andrei Jechiu
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...Vlad Savitsky
 
Drupal 8 preview_slideshow
Drupal 8 preview_slideshowDrupal 8 preview_slideshow
Drupal 8 preview_slideshowTee Malapela
 
GTU MCA PHP Interview Questions And Answers for freshers
GTU MCA PHP  Interview Questions And Answers for freshersGTU MCA PHP  Interview Questions And Answers for freshers
GTU MCA PHP Interview Questions And Answers for freshersTOPS Technologies
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesShabir Ahmad
 
Approaches to machine actionable links
Approaches to machine actionable linksApproaches to machine actionable links
Approaches to machine actionable linksStephen Richard
 
Comparison of different access controls
Comparison of different access controlsComparison of different access controls
Comparison of different access controlsRashmi Nair
 
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011jbarclay
 

Similar to Services, dependency injection and containers (20)

Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphony
 
Symfony and Drupal 8
Symfony and Drupal 8Symfony and Drupal 8
Symfony and Drupal 8
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
 
Drupal 8 Vocabulary Lesson
Drupal 8 Vocabulary LessonDrupal 8 Vocabulary Lesson
Drupal 8 Vocabulary Lesson
 
Software Development with PHP & Laravel
Software Development  with PHP & LaravelSoftware Development  with PHP & Laravel
Software Development with PHP & Laravel
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in php
 
.Net template solution architecture
.Net template solution architecture.Net template solution architecture
.Net template solution architecture
 
Services in Drupal 8
Services in Drupal 8Services in Drupal 8
Services in Drupal 8
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...
Yuriy Gerasimov. Drupal Services. Integration with third party applications. ...
 
Drupal 8 preview_slideshow
Drupal 8 preview_slideshowDrupal 8 preview_slideshow
Drupal 8 preview_slideshow
 
GTU MCA PHP Interview Questions And Answers for freshers
GTU MCA PHP  Interview Questions And Answers for freshersGTU MCA PHP  Interview Questions And Answers for freshers
GTU MCA PHP Interview Questions And Answers for freshers
 
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
Jones "Working with Scholarly APIs: A NISO Training Series, Session One: Foun...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API Changes
 
Approaches to machine actionable links
Approaches to machine actionable linksApproaches to machine actionable links
Approaches to machine actionable links
 
Comparison of different access controls
Comparison of different access controlsComparison of different access controls
Comparison of different access controls
 
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011
Drupal 7 Feeds Intro Drupal Camp Indianapolis 2011
 

Recently uploaded

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapIshara Amarasekera
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsDEEPRAJ PATHAK
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...OnePlan Solutions
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...kalichargn70th171
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 

Recently uploaded (20)

Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery Roadmap
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software Projects
 
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
Revolutionizing the Digital Transformation Office - Leveraging OnePlan’s AI a...
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
The Ultimate Guide to Performance Testing in Low-Code, No-Code Environments (...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 

Services, dependency injection and containers

  • 1. Services, Dependency Injection and Containers In Drupal 8
  • 2. About Me Sushil Hanwate Twitter: @thesushyl Drupal Developer @
  • 3. What is a Service? A Service is any PHP object that performs some sort of "global" task. It's a purposefully-generic name used in computer science to describe an object that's created for a specific purpose (e.g. delivering emails). As a rule, a PHP object is a service if it is used globally in your application.
  • 4. Defining Services // user.services.yml services: access_check.permission: class: DrupaluserAccessPermissionAccessCheck // ‘modules/user/src/access/PermissionAccessCheck.php’ tags: - { name: access_check, applies_to: _permission } // core.services.yml services: path.alias_manager: class: DrupalCorePathAliasManager // ‘/core/lib/drupal/core/path/AliasManager.php’ arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data']
  • 5. Obtaining Services Service Location (Procedural) Dependency Injection (Used in classes)
  • 6. Obtaining Services: Service Location // Get service from outside of a class. $service = Drupal::service('service_name'); // If you have $container variable $service = $container->get('service_name'); // Example services $cache = Drupal::cache(); $lock = Drupal::lock()->acquire($lock_name)
  • 7. Obtaining Services: Service Location // Source $cache = Drupal::cache();
  • 8. Dependency Injection - Definition Dependency injection is a software design pattern in which one or more dependencies/services are injected, or passed by reference , into a dependent object/client and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles.
  • 9. Obtaining Services: Dependency Injection 1. DI is used in classes. 2. If your class is a service, inject dependencies via arguments in *.services.yml services: path.alias_manager: class: DrupalCorePathAliasManager // ‘/core/lib/drupal/core/path/AliasManager.php’ arguments: ['@path.alias_storage', '@path.alias_whitelist', '@language_manager', '@cache.data'] // code public function __construct (AliasStorageInterface $storage, AliasWhitelistInterface $whitelist, LanguageManagerInterface $language_manager, CacheBackendInterface $cache) {
  • 10. Overriding Services 1. Locate default class and interface 2. Define a class that provides same services with different way implementing interface and/or overriding the class, say Drupalfoo_barMyNewServiceClass 1. Define a class that implements DrupalCoreDependencyInjectionServiceModifierInterface called Drupalfoo_barFooBarServiceProvider 2. Put this in alter() method public function alter(ContainerBuilder $container) { $definition = $container->getDefinition('service.name'); $definition->setClass(Drupalfoo_barMyNewServiceClass); }