SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
Dependency 
Injection 
in Drupal 8 
Greg Szczotka 
Drupal Camp Wrocław 
19.10.2014
About me 
Greg Szczotka @greg606 
● Lead Developer @ Creaticon 
● angielski-online.pl (Joomla) 
● PHP trainer @ Quali
Drupal 8, welcome to OO!
Why change is hard? 
“Object-oriented design is about managing dependencies. It is a set of coding 
techniques that arrange dependencies such that objects can tolerate change. 
In the absence of design, unmanaged dependencies wreak havoc because 
objects know too much about one another. Changing one object forces change 
upon its collaborators, which in turn, forces change upon its collaborators, ad 
infinitum. A seemingly insignificant enhancement can cause damage that 
radiates outward in overlapping concentric circles, ultimately leaving no code 
untouched. 
When objects know too much they have many expectations about the world in 
which they reside. They’re picky, they need things to be “just so.” These 
expectations constrain them. The objects resist being reused in different 
contexts; they are painful to test and susceptible to being duplicated.” 
Sandi Metz. “Practical Object-Oriented Design in Ruby: An Agile Primer (Jason Arnold's Library).”
“Because well designed objects have a single 
responsibility, their very nature requires that they 
collaborate to accomplish complex tasks. This collaboration 
is powerful and perilous. To collaborate, an object must 
know something know about others. Knowing creates a 
dependency. If not managed carefully, these dependencies 
will strangle your application.” 
Sandi Metz. “Practical Object-Oriented Design in Ruby: An Agile Primer (Jason Arnold's Library).”
Dependency Injection 
"Dependency Injection" is a 25-dollar 
term for a 5-cent concept.
Depenency Injection - Definition 
« Dependency Injection is where components are given 
their dependencies through their constructors, methods, or 
directly into fields. »
Why DI ? 
Goal: we want to write code that is... 
✔ Clutter-free 
✔ Reusable 
✔ Testable
An injection is the passing of a dependency (a service) to a 
dependent object (a client). 
The service is made part of the client's state. Passing the 
service to the client, rather than allowing a client to build or 
find the service, is the fundamental requirement of the 
pattern.
What are dependencies? 
● framework 
● third party libraries 
● database 
● filesystem 
● email 
● web services 
● system resources (Clock) 
● configuration 
● the new keyword 
● static methods 
● random
Before DI 
class A 
{ 
public function a1() { 
$b = new B(); 
$b->b1(); 
} 
}
class Flashcard 
{ 
private $db; 
public function __construct() 
{ 
hard to customize 
$this->db = new new MysqlConnection('flashcards'); 
} 
} 
$flashcard = new Flashcard(); 
easy to use
Types of DI 
- constructor injection 
- setter injection 
- interface injection 
- property injection
DI - Constructor Injection 
class Flashcard 
{ 
private $db; 
public function __construct(MySqlConnection $db) 
{ 
$this->db = $db; 
} 
} 
$db = new MySQLConnection(); 
$flashcard = new Flashcard($db); 
slightly more difficult to use
DI - Setter Injection 
class Flashcard 
{ 
private $db; 
public setDb(MySqlConnection $db) 
{ 
$this->db = $db; 
} 
}
Dependency injection is a software design 
pattern that implements inversion of control and 
allows a program design to follow the 
dependency inversion principle.
SOLID 
● Single responsibility, 
● Open-closed, 
● Liskov substitution, 
● Interface segregation, 
● Dependency inversion
Depend on abstractions, not on concretions.
Dependency Inversion Principle 
A. High-level modules should not depend on low-level modules. 
Both should depend on abstractions. 
B. Abstractions should not depend on details. 
Details should depend on abstractions.
class Flashcard 
{ 
private $db; 
public function __construct(MySqlConnection $db) 
{ 
$this->db = $db; 
} 
}
interface ConnectionInterface { 
public function connect(); 
} 
class DbConnection implements ConnectionInterface { 
public function connect() { 
//do something 
}; 
}class Flashcard { 
public function __construct(ConnectionInterface $connection){ 
$this->connection = $connection; 
} 
} 
$db = new DbConnection(); 
$flashcard = new Flashcard($db);
Dependency Injection 
== 
Inversion of Control
Inversion of Control 
A design in which custom-written portions of a computer program receive the 
flow of control from a generic, reusable library. 
A software architecture with this design inverts control as compared to 
traditional procedural programming: in traditional programming, the custom 
code that expresses the purpose of the program calls into reusable libraries to 
take care of generic tasks, but with inversion of control, it is the reusable code 
that calls into the custom, or task-specific, code.
IoC = Hollywood Principle 
"don't call us, we'll call you." 
Instead of your program running the system, the system runs your program.
Inversion of Control - Why? 
● To decouple the execution of a task from implementation. 
● To focus a module on the task it is designed for. 
● To free modules from assumptions about how other 
systems do what they do and instead rely on contracts. 
● To prevent side effects when replacing a module.
IoC - implementations 
● factory pattern 
● service locator pattern 
● dependency injection 
● contextualized lookup 
● template method pattern 
● strategy pattern
The less your code knows, the 
more reusable it is.
DI - Problem 
$transport = new 
Zend_Mail_Transport_Smtp('smtp.gmail.com', array( 
'auth' => 'login', 
'username' => 'foo', 
'password' => 'bar', 
'ssl' => 'ssl', 
'port' => 465, 
)); 
$mailer = new Zend_Mail(); 
$mailer->setDefaultTransport($transport);
Dependency Injection Container 
A Dependency Injection Container is an object that 
knows how to instantiate and configure objects. 
And to be able to do its job, it needs to knows about the 
constructor arguments and the relationships between the 
objects. 
These objects are called Services.
How does it work? 
➔ Service keys map to service definitions 
➔ Definitions specify which class to instantiate and what its 
dependencies are 
➔ Dependencies are specified as references to other 
services (using service keys) 
➔ $container->getService('some_service')
Service Container 
➔ Assumes responsibility for constructing object graphs 
(i.e. instantiating your classes with their dependencies) 
➔ Uses configuration data to know how to do this 
➔ Allows infrastructure logic to be kept separate from 
application logic
What is Service? 
A service is any PHP class that performs an action. 
A service is an object that provides some kind of 
globally useful functionality 
“A service is an object, registered at the service container 
under a certain id. ” 
Matthias Noback. “A Year With Symfony.”
Examples of Services 
➔ Cache Backend 
➔ Logger 
➔ Mailer 
➔ URL Generator
Examples of NOT Services 
➔ Product 
➔ Blog post 
➔ Email message
Symfony DI Component 
The DependencyInjection component allows you to standardize and 
centralize the way objects are constructed in your application.
Symfony DI Component 
● Default scope: container 
● Can be configured in PHP, XML or YAML 
● Can be “compiled” down to plain PHP
SDIC - Compiling the container 
It's too expensive to parse configuration on 
every request. 
Parse once and put the result into a PHP class 
that hardcodes a method for each service.
SDIC - Compiling the container 
serialization.json: 
class: DrupalComponentSerializationJson 
class service_container extends Container { 
public function getSerialization_JsonService() 
{ return $this->services['serialization.json'] = 
new DrupalComponentSerializationJson(); 
} 
}
SDIC - Compiling the container 
public function getStateSevice() 
{ return $this->services['state'] = 
new DrupalCoreStateState( 
$this->get('keyvalue') 
); 
}
Some D8 Services 
➔ The default DB connection ('database') 
➔ The module handler ('module_handler') 
➔ The HTTP request object ('request')
D8 Core Services 
CoreServiceProvider.php and core.services.yml 
language_manager: 
class: DrupalCoreLanguageLanguageManager 
arguments: ['@language.default'] 
path.alias_manager: 
class: DrupalCorePathAliasManager 
arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager'] 
string_translation: 
class: DrupalCoreStringTranslationTranslationManager 
breadcrumb: 
class: DrupalCoreBreadcrumbBreadcrumbManager 
arguments: ['@module_handler']
Don't inject the container! 
Ever. 
(Unless you absolutely must)
Service Definition 
module_name.services.yml 
services: 
demo.demo_service: 
class: DrupaldemoDemoService
Service Definition - Arguments 
module_handler: 
class: DrupalCoreExtensionModuleHandler 
arguments: ['%container.modules%', '@cache.bootstrap']
Service Definition - Calls 
class_resolver: 
class: DrupalCoreDependencyInjectionClassResolver 
calls: 
- [setContainer, ['@service_container']]
Service Definition - Factory 
database: 
class: DrupalCoreDatabaseConnection 
factory_class: DrupalCoreDatabaseDatabase 
factory_method: getConnection 
arguments: [default]
Service Definition - Factory Service 
cache.default: 
class: DrupalCoreCacheCacheBackendInterface 
tags: 
- { name: cache.bin } 
factory_method: get 
factory_service: cache_factory 
arguments: [default]
Service Definition - Alias 
twig.loader: 
alias: twig.loader.filesystem
Service Definition - Abstract/Parent 
default_plugin_manager: 
abstract: true 
arguments: ['@container.namespaces', '@cache.discovery', 
'@module_handler'] 
plugin.manager.archiver: 
class: DrupalCoreArchiverArchiverManager 
parent: default_plugin_manager
Service Definition - Public 
config.storage.active: 
class: DrupalCoreConfigDatabaseStorage 
arguments: ['@database', 'config'] 
public: false 
tags: 
- { name: backend_overridable }config.storage.file: 
class: DrupalCoreConfigFileStorage 
factory_class: DrupalCoreConfigFileStorageFactory 
factory_method: getActive 
public: false
D8 - how to get service? 
● Drupal::getContainer()->get('url_generator') 
● Drupal::service('url_generator') 
● Drupal::urlGenerator() 
please don’t! 
INJECT LIKE HELL
D8 - Service Implementation 
namespace Drupaldemo; 
class DemoService { 
protected $demo_value; 
public function __construct() { 
$this->demo_value = 'Upchuk'; 
} 
public function getDemoValue() { return $this- 
>demo_value; 
} 
}
D8 - Controller 
class DemoController extends ControllerBase { 
public function demo() { return array( 
'#markup' => t('Hello @value!', array('@value' => $this- 
>demoService->getDemoValue())), 
); 
} 
}
D8 - Controller 
class DemoController extends ControllerBase { 
protected $demoService; 
public function __construct($demoService) { 
$this->demoService = $demoService; 
} 
public static function create(ContainerInterface $container) 
{ return new static( 
$container->get('demo.demo_service') 
); 
} 
}
D8 - DI for a form 
class ExampleForm extends FormBase { 
public function __construct(AccountInterface $account) { 
$this->account = $account; 
} 
public static function create(ContainerInterface $container) { 
// Instantiates this form class. return new static( 
// Load the service required to construct this class. 
$container->get('current_user') 
); 
} 
}
D8 - Altering existing services, providing dynamic services 
namespace Drupalmy_module;use DrupalCoreDependencyInjection 
ContainerBuilder;use DrupalCoreDependencyInjection 
ServiceProviderBase;class MyModuleServiceProvider extends 
ServiceProviderBase { 
public function alter(ContainerBuilder $container) { 
// Overrides language_manager class to test domain language 
negotiation. 
$definition = $container->getDefinition('language_manager'); 
$definition->setClass('Drupallanguage_testLanguageTestManager'); 
} 
}
Service tags 
services: 
foo.twig.extension: 
class: DcwrocHelloBundleExtensionFooExtension 
tags: 
- { name: twig.extension }
D8 Service Tags 
access_check 
authentication_provider 
breadcrumb_builder 
cache.bin 
cache.context 
config.factory.override 
encoder 
entity_resolver 
event_subscriber 
needs_destruction 
normalizer 
paramconverter 
path_processor_inbound 
persist 
plugin_manager_cache_clear 
route_enhancer 
route_filter 
route_processor_outbound 
string_translator 
theme_negotiator 
twig.extension
Resources 
● Inversion of Control Containers and the Dependency 
Injection pattern 
● Symfony Service Container 
● The DependencyInjection Component 
● Services and dependency injection in Drupal 8
Dependency injection Drupal Camp Wrocław 2014

Contenu connexe

Tendances

MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataChris Richardson
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB
 
Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]Payara
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Sameer Rathoud
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionDinesh Sharma
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice PresentationDmitry Buzdin
 
Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]Gaurav Gupta
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questionsppratik86
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinPeter Lehto
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus Inc.
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot missMark Papis
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingAnalyticsConf
 
Building impressive layout systems with vaadin
Building impressive layout systems with vaadinBuilding impressive layout systems with vaadin
Building impressive layout systems with vaadinPeter Lehto
 

Tendances (20)

MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring Data
 
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011MongoDB for Java Devs with Spring Data - MongoPhilly 2011
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
 
Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]Rapid development tools for java ee 8 [tut2998]
Rapid development tools for java ee 8 [tut2998]
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Proxy Pattern
Proxy PatternProxy Pattern
Proxy Pattern
 
Jug Guice Presentation
Jug Guice PresentationJug Guice Presentation
Jug Guice Presentation
 
Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]Rapid Development Tools for Java EE 8 [TUT2998]
Rapid Development Tools for Java EE 8 [TUT2998]
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with Vaadin
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss9 crucial Java Design Principles you cannot miss
9 crucial Java Design Principles you cannot miss
 
Google Guice
Google GuiceGoogle Guice
Google Guice
 
Wiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programmingWiesław Kałkus: C# functional programming
Wiesław Kałkus: C# functional programming
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
Building impressive layout systems with vaadin
Building impressive layout systems with vaadinBuilding impressive layout systems with vaadin
Building impressive layout systems with vaadin
 

Similaire à Dependency injection Drupal Camp Wrocław 2014

Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Nelson Gomes
 
Content Staging in Drupal 8
Content Staging in Drupal 8Content Staging in Drupal 8
Content Staging in Drupal 8Dick Olsson
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVPHarshith Keni
 
Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLADependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLAAshwini Kumar
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to DomainJeremy Cook
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
Easy integration of Bluemix services with your applications
Easy integration of Bluemix services with your applicationsEasy integration of Bluemix services with your applications
Easy integration of Bluemix services with your applicationsJack-Junjie Cai
 
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"GlobalLogic Ukraine
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1guest075fec
 
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...DicodingEvent
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginnersMunir Hoque
 
Николай Паламарчук "Управление зависимостями в больших проектах"
Николай Паламарчук "Управление зависимостями в больших проектах" Николай Паламарчук "Управление зависимостями в больших проектах"
Николай Паламарчук "Управление зависимостями в больших проектах" Fwdays
 
Java Programming
Java ProgrammingJava Programming
Java ProgrammingTracy Clark
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNicole Gomez
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Miguel Gallardo
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 

Similaire à Dependency injection Drupal Camp Wrocław 2014 (20)

Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.Codebits 2012 - Fast relational web site construction.
Codebits 2012 - Fast relational web site construction.
 
Content Staging in Drupal 8
Content Staging in Drupal 8Content Staging in Drupal 8
Content Staging in Drupal 8
 
Solid OOPS
Solid OOPSSolid OOPS
Solid OOPS
 
React & redux
React & reduxReact & redux
React & redux
 
Angular js
Angular jsAngular js
Angular js
 
OOP, API Design and MVP
OOP, API Design and MVPOOP, API Design and MVP
OOP, API Design and MVP
 
Dependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLADependency injection in Drupal 8 : DrupalCon NOLA
Dependency injection in Drupal 8 : DrupalCon NOLA
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
Easy integration of Bluemix services with your applications
Easy integration of Bluemix services with your applicationsEasy integration of Bluemix services with your applications
Easy integration of Bluemix services with your applications
 
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
Java TechTalk "Spring boot made life easier with Kubernetes and Microservices"
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1
 
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...
Dicoding Developer Coaching #31: Android | Menerapkan Clean Architecture di A...
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
Николай Паламарчук "Управление зависимостями в больших проектах"
Николай Паламарчук "Управление зависимостями в больших проектах" Николай Паламарчук "Управление зависимостями в больших проектах"
Николай Паламарчук "Управление зависимостями в больших проектах"
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Nt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language AnalysisNt1310 Unit 3 Language Analysis
Nt1310 Unit 3 Language Analysis
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 

Dernier

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Dernier (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Dependency injection Drupal Camp Wrocław 2014

  • 1. Dependency Injection in Drupal 8 Greg Szczotka Drupal Camp Wrocław 19.10.2014
  • 2. About me Greg Szczotka @greg606 ● Lead Developer @ Creaticon ● angielski-online.pl (Joomla) ● PHP trainer @ Quali
  • 4. Why change is hard? “Object-oriented design is about managing dependencies. It is a set of coding techniques that arrange dependencies such that objects can tolerate change. In the absence of design, unmanaged dependencies wreak havoc because objects know too much about one another. Changing one object forces change upon its collaborators, which in turn, forces change upon its collaborators, ad infinitum. A seemingly insignificant enhancement can cause damage that radiates outward in overlapping concentric circles, ultimately leaving no code untouched. When objects know too much they have many expectations about the world in which they reside. They’re picky, they need things to be “just so.” These expectations constrain them. The objects resist being reused in different contexts; they are painful to test and susceptible to being duplicated.” Sandi Metz. “Practical Object-Oriented Design in Ruby: An Agile Primer (Jason Arnold's Library).”
  • 5. “Because well designed objects have a single responsibility, their very nature requires that they collaborate to accomplish complex tasks. This collaboration is powerful and perilous. To collaborate, an object must know something know about others. Knowing creates a dependency. If not managed carefully, these dependencies will strangle your application.” Sandi Metz. “Practical Object-Oriented Design in Ruby: An Agile Primer (Jason Arnold's Library).”
  • 6. Dependency Injection "Dependency Injection" is a 25-dollar term for a 5-cent concept.
  • 7. Depenency Injection - Definition « Dependency Injection is where components are given their dependencies through their constructors, methods, or directly into fields. »
  • 8. Why DI ? Goal: we want to write code that is... ✔ Clutter-free ✔ Reusable ✔ Testable
  • 9. An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.
  • 10. What are dependencies? ● framework ● third party libraries ● database ● filesystem ● email ● web services ● system resources (Clock) ● configuration ● the new keyword ● static methods ● random
  • 11. Before DI class A { public function a1() { $b = new B(); $b->b1(); } }
  • 12. class Flashcard { private $db; public function __construct() { hard to customize $this->db = new new MysqlConnection('flashcards'); } } $flashcard = new Flashcard(); easy to use
  • 13. Types of DI - constructor injection - setter injection - interface injection - property injection
  • 14. DI - Constructor Injection class Flashcard { private $db; public function __construct(MySqlConnection $db) { $this->db = $db; } } $db = new MySQLConnection(); $flashcard = new Flashcard($db); slightly more difficult to use
  • 15. DI - Setter Injection class Flashcard { private $db; public setDb(MySqlConnection $db) { $this->db = $db; } }
  • 16. Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle.
  • 17. SOLID ● Single responsibility, ● Open-closed, ● Liskov substitution, ● Interface segregation, ● Dependency inversion
  • 18.
  • 19. Depend on abstractions, not on concretions.
  • 20. Dependency Inversion Principle A. High-level modules should not depend on low-level modules. Both should depend on abstractions. B. Abstractions should not depend on details. Details should depend on abstractions.
  • 21. class Flashcard { private $db; public function __construct(MySqlConnection $db) { $this->db = $db; } }
  • 22. interface ConnectionInterface { public function connect(); } class DbConnection implements ConnectionInterface { public function connect() { //do something }; }class Flashcard { public function __construct(ConnectionInterface $connection){ $this->connection = $connection; } } $db = new DbConnection(); $flashcard = new Flashcard($db);
  • 23. Dependency Injection == Inversion of Control
  • 24. Inversion of Control A design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library. A software architecture with this design inverts control as compared to traditional procedural programming: in traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the reusable code that calls into the custom, or task-specific, code.
  • 25. IoC = Hollywood Principle "don't call us, we'll call you." Instead of your program running the system, the system runs your program.
  • 26. Inversion of Control - Why? ● To decouple the execution of a task from implementation. ● To focus a module on the task it is designed for. ● To free modules from assumptions about how other systems do what they do and instead rely on contracts. ● To prevent side effects when replacing a module.
  • 27. IoC - implementations ● factory pattern ● service locator pattern ● dependency injection ● contextualized lookup ● template method pattern ● strategy pattern
  • 28. The less your code knows, the more reusable it is.
  • 29. DI - Problem $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', array( 'auth' => 'login', 'username' => 'foo', 'password' => 'bar', 'ssl' => 'ssl', 'port' => 465, )); $mailer = new Zend_Mail(); $mailer->setDefaultTransport($transport);
  • 30. Dependency Injection Container A Dependency Injection Container is an object that knows how to instantiate and configure objects. And to be able to do its job, it needs to knows about the constructor arguments and the relationships between the objects. These objects are called Services.
  • 31.
  • 32. How does it work? ➔ Service keys map to service definitions ➔ Definitions specify which class to instantiate and what its dependencies are ➔ Dependencies are specified as references to other services (using service keys) ➔ $container->getService('some_service')
  • 33. Service Container ➔ Assumes responsibility for constructing object graphs (i.e. instantiating your classes with their dependencies) ➔ Uses configuration data to know how to do this ➔ Allows infrastructure logic to be kept separate from application logic
  • 34. What is Service? A service is any PHP class that performs an action. A service is an object that provides some kind of globally useful functionality “A service is an object, registered at the service container under a certain id. ” Matthias Noback. “A Year With Symfony.”
  • 35. Examples of Services ➔ Cache Backend ➔ Logger ➔ Mailer ➔ URL Generator
  • 36. Examples of NOT Services ➔ Product ➔ Blog post ➔ Email message
  • 37. Symfony DI Component The DependencyInjection component allows you to standardize and centralize the way objects are constructed in your application.
  • 38. Symfony DI Component ● Default scope: container ● Can be configured in PHP, XML or YAML ● Can be “compiled” down to plain PHP
  • 39. SDIC - Compiling the container It's too expensive to parse configuration on every request. Parse once and put the result into a PHP class that hardcodes a method for each service.
  • 40. SDIC - Compiling the container serialization.json: class: DrupalComponentSerializationJson class service_container extends Container { public function getSerialization_JsonService() { return $this->services['serialization.json'] = new DrupalComponentSerializationJson(); } }
  • 41. SDIC - Compiling the container public function getStateSevice() { return $this->services['state'] = new DrupalCoreStateState( $this->get('keyvalue') ); }
  • 42. Some D8 Services ➔ The default DB connection ('database') ➔ The module handler ('module_handler') ➔ The HTTP request object ('request')
  • 43. D8 Core Services CoreServiceProvider.php and core.services.yml language_manager: class: DrupalCoreLanguageLanguageManager arguments: ['@language.default'] path.alias_manager: class: DrupalCorePathAliasManager arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager'] string_translation: class: DrupalCoreStringTranslationTranslationManager breadcrumb: class: DrupalCoreBreadcrumbBreadcrumbManager arguments: ['@module_handler']
  • 44. Don't inject the container! Ever. (Unless you absolutely must)
  • 45. Service Definition module_name.services.yml services: demo.demo_service: class: DrupaldemoDemoService
  • 46. Service Definition - Arguments module_handler: class: DrupalCoreExtensionModuleHandler arguments: ['%container.modules%', '@cache.bootstrap']
  • 47. Service Definition - Calls class_resolver: class: DrupalCoreDependencyInjectionClassResolver calls: - [setContainer, ['@service_container']]
  • 48. Service Definition - Factory database: class: DrupalCoreDatabaseConnection factory_class: DrupalCoreDatabaseDatabase factory_method: getConnection arguments: [default]
  • 49. Service Definition - Factory Service cache.default: class: DrupalCoreCacheCacheBackendInterface tags: - { name: cache.bin } factory_method: get factory_service: cache_factory arguments: [default]
  • 50. Service Definition - Alias twig.loader: alias: twig.loader.filesystem
  • 51. Service Definition - Abstract/Parent default_plugin_manager: abstract: true arguments: ['@container.namespaces', '@cache.discovery', '@module_handler'] plugin.manager.archiver: class: DrupalCoreArchiverArchiverManager parent: default_plugin_manager
  • 52. Service Definition - Public config.storage.active: class: DrupalCoreConfigDatabaseStorage arguments: ['@database', 'config'] public: false tags: - { name: backend_overridable }config.storage.file: class: DrupalCoreConfigFileStorage factory_class: DrupalCoreConfigFileStorageFactory factory_method: getActive public: false
  • 53. D8 - how to get service? ● Drupal::getContainer()->get('url_generator') ● Drupal::service('url_generator') ● Drupal::urlGenerator() please don’t! INJECT LIKE HELL
  • 54. D8 - Service Implementation namespace Drupaldemo; class DemoService { protected $demo_value; public function __construct() { $this->demo_value = 'Upchuk'; } public function getDemoValue() { return $this- >demo_value; } }
  • 55. D8 - Controller class DemoController extends ControllerBase { public function demo() { return array( '#markup' => t('Hello @value!', array('@value' => $this- >demoService->getDemoValue())), ); } }
  • 56. D8 - Controller class DemoController extends ControllerBase { protected $demoService; public function __construct($demoService) { $this->demoService = $demoService; } public static function create(ContainerInterface $container) { return new static( $container->get('demo.demo_service') ); } }
  • 57. D8 - DI for a form class ExampleForm extends FormBase { public function __construct(AccountInterface $account) { $this->account = $account; } public static function create(ContainerInterface $container) { // Instantiates this form class. return new static( // Load the service required to construct this class. $container->get('current_user') ); } }
  • 58. D8 - Altering existing services, providing dynamic services namespace Drupalmy_module;use DrupalCoreDependencyInjection ContainerBuilder;use DrupalCoreDependencyInjection ServiceProviderBase;class MyModuleServiceProvider extends ServiceProviderBase { public function alter(ContainerBuilder $container) { // Overrides language_manager class to test domain language negotiation. $definition = $container->getDefinition('language_manager'); $definition->setClass('Drupallanguage_testLanguageTestManager'); } }
  • 59. Service tags services: foo.twig.extension: class: DcwrocHelloBundleExtensionFooExtension tags: - { name: twig.extension }
  • 60. D8 Service Tags access_check authentication_provider breadcrumb_builder cache.bin cache.context config.factory.override encoder entity_resolver event_subscriber needs_destruction normalizer paramconverter path_processor_inbound persist plugin_manager_cache_clear route_enhancer route_filter route_processor_outbound string_translator theme_negotiator twig.extension
  • 61. Resources ● Inversion of Control Containers and the Dependency Injection pattern ● Symfony Service Container ● The DependencyInjection Component ● Services and dependency injection in Drupal 8