SlideShare a Scribd company logo
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 Results
Kris Buytaert
 
Workflow Initiative
Workflow InitiativeWorkflow Initiative
Workflow Initiative
timmillwood
 
Hack Proof Your Drupal Site
Hack Proof Your Drupal SiteHack Proof Your Drupal Site
Hack Proof Your Drupal Site
Naveen 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 Media
ffnatania
 
Continuous Integration & Drupal
Continuous Integration & DrupalContinuous Integration & Drupal
Continuous Integration & Drupal
LimoenGroen
 
Message Queues and Drupal
Message Queues and DrupalMessage Queues and Drupal
Message Queues and Drupal
Brian Altenhofel
 
Grok Drupal (7) Theming
Grok Drupal (7) ThemingGrok Drupal (7) Theming
Grok Drupal (7) Theming
PINGV
 
D7 theming what's new - London
D7 theming what's new - LondonD7 theming what's new - London
D7 theming what's new - London
Marek Sotak
 
Fundraising with Drupal
Fundraising with DrupalFundraising with Drupal
Fundraising with Drupal
Lev 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.3
Kris Wallsmith
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
Karwin Software Solutions LLC
 

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 symphony
Brahampal Singh
 
Symfony and Drupal 8
Symfony and Drupal 8Symfony and Drupal 8
Symfony and Drupal 8
Kunal Kursija
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
Durgesh Tripathi
 
Drupal 8 Vocabulary Lesson
Drupal 8 Vocabulary LessonDrupal 8 Vocabulary Lesson
Drupal 8 Vocabulary Lesson
Mediacurrent
 
Software Development with PHP & Laravel
Software Development  with PHP & LaravelSoftware Development  with PHP & Laravel
Software Development with PHP & Laravel
Juan Victor Minaya León
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
Sudip Simkhada
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in php
SHIVANI SONI
 
.Net template solution architecture
.Net template solution architecture.Net template solution architecture
.Net template solution architecture
Diogo Gonçalves da Cunha
 
Services in Drupal 8
Services in Drupal 8Services in Drupal 8
Services in Drupal 8
Andrei Jechiu
 
Java Technology
Java TechnologyJava Technology
Java Technology
ifnu 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_slideshow
Tee 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 freshers
TOPS Technologies
 
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...
National Information Standards Organization (NISO)
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
LEDC 2016
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
Valentine Matsveiko
 
Drupal 8 - Core and API Changes
Drupal 8 - Core and API ChangesDrupal 8 - Core and API Changes
Drupal 8 - Core and API Changes
Shabir Ahmad
 
Approaches to machine actionable links
Approaches to machine actionable linksApproaches to machine actionable links
Approaches to machine actionable links
Stephen Richard
 
Comparison of different access controls
Comparison of different access controlsComparison of different access controls
Comparison of different access controls
Rashmi 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 2011
jbarclay
 

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...
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
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

Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
Alina Yurenko
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
What’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 UpdateWhat’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 Update
VictoriaMetrics
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
widenerjobeyrl638
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
ervikas4
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
Zycus
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
confluent
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
Anand Bagmar
 
Trailhead Talks_ Journey of an All-Star Ranger .pptx
Trailhead Talks_ Journey of an All-Star Ranger .pptxTrailhead Talks_ Journey of an All-Star Ranger .pptx
Trailhead Talks_ Journey of an All-Star Ranger .pptx
ImtiazBinMohiuddin
 
Best Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP ImplementationBest Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP Implementation
Envertis Software Solutions
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Applitools
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
kalichargn70th171
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
The Third Creative Media
 

Recently uploaded (20)

Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
Going AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applicationsGoing AOT: Everything you need to know about GraalVM for Java applications
Going AOT: Everything you need to know about GraalVM for Java applications
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
What’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 UpdateWhat’s new in VictoriaMetrics - Q2 2024 Update
What’s new in VictoriaMetrics - Q2 2024 Update
 
bgiolcb
bgiolcbbgiolcb
bgiolcb
 
Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
美洲杯赔率投注网【​网址​🎉3977·EE​🎉】
 
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptxMigration From CH 1.0 to CH 2.0 and  Mule 4.6 & Java 17 Upgrade.pptx
Migration From CH 1.0 to CH 2.0 and Mule 4.6 & Java 17 Upgrade.pptx
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
How GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdfHow GenAI Can Improve Supplier Performance Management.pdf
How GenAI Can Improve Supplier Performance Management.pdf
 
Building API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructureBuilding API data products on top of your real-time data infrastructure
Building API data products on top of your real-time data infrastructure
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
Streamlining End-to-End Testing Automation
Streamlining End-to-End Testing AutomationStreamlining End-to-End Testing Automation
Streamlining End-to-End Testing Automation
 
Trailhead Talks_ Journey of an All-Star Ranger .pptx
Trailhead Talks_ Journey of an All-Star Ranger .pptxTrailhead Talks_ Journey of an All-Star Ranger .pptx
Trailhead Talks_ Journey of an All-Star Ranger .pptx
 
Best Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP ImplementationBest Practices & Tips for a Successful Odoo ERP Implementation
Best Practices & Tips for a Successful Odoo ERP Implementation
 
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual PerfectionBuilding the Ideal CI-CD Pipeline_ Achieving Visual Perfection
Building the Ideal CI-CD Pipeline_ Achieving Visual Perfection
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdf
 
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
Unlock the Secrets to Effortless Video Creation with Invideo: Your Ultimate G...
 

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); }