SlideShare a Scribd company logo
Dependency Injection Smells
Featuring Zend,Symfonyand Doctrinecode
Matthias Noback - PHP developer and consultant
Dutch PHP Conference - 6/7/2013
Matthias Noback
Dutch developer
Consultancy, training, writing
Clean code
·
·
·
2/44
What is a dependency?
A needs a B to do its job
therefore
B is a dependency of A
3/44
Dependency management
To make sure that A will have a B, A can:
4/44
1. Create a B
5/44
2. Fetch a B
6/44
3. Receive a B
7/44
Dependency management
Strategy 1: Do it yourself
8/44
Why not...
Instantiate classes with the newoperator?
classSomeClass
{
publicfunctiondoSomething()
{
$logger=newLogger();
$logger->debug('Nothingtoseehere');
}
}
PHP
9/44
Why not...
Instantiate variable classes?
classSomeClass
{
publicfunction__construct($loggerClass)
{
$this->loggerClass=$loggerClass;
}
publicfunctiondoSomething()
{
$logger=new{$this->loggerClass}();
$logger->debug('Veryflexible,right?');
}
}
PHP
10/44
Why not...
Instantiate in overridable methods?
classSomeClass
{
publicfunctiondoSomething()
{
$logger=$this->createLogger();
$logger->debug('Matthiaswashere');
}
protectedfunctioncreateLogger()
{
returnnewLogger();
}
}
PHP
11/44
Dependency management
Strategy 2: Fetch your dependencies
12/44
Why not...
Use a global/static variable?
classSomeClass
{
publicfunctiondoSomething()
{
Logger::getInstance()->debug('Matthiaswashere');
}
}
PHP
13/44
Why not...
Use a service container/manager/registry?
classSomeClass
{
publicfunction__construct(ContainerInterface$container)
{
$this->container=$container;
}
publicfunctiondoSomething()
{
$this
->container
->get('logger')
->log('Wow,thatwasquiteadistance!')
}
}
PHP
14/44
Dependency management
Strategy 3: Be passive about your dependencies
15/44
Injecting dependencies by their interface
classSomeClass
{
publicfunction__construct(LoggerInterface$logger)
{
$this->logger=$logger;
}
publicfunctiondoSomething()
{
$this->logger->info('Ah,muchbetter');
}
}
PHP
16/44
Strategy review
1. Create your own dependencies
2. Fetch your dependencies
17/44
Strategy review
You are in control of your dependencies
18/44
Strategy review
3. Have your dependencies injected
19/44
Strategy review
You are not in control of your dependencies
Someone else
This is called "inversion of control" (IoC)
·
·
·
20/44
Dependency injection
Dependency injection is a ,
used to
21/44
Code review
ZendCrypt
Code review
ZendCrypt
classBlockCipher
{
publicfunction__construct(SymmetricInterface$cipher)
{
$this->cipher=$cipher;
}
publicfunctionencrypt($data)
{
...
}
publicfunctiondecrypt($data)
{
...
}
}
PHP
23/44
ZendCrypt
Dependency Injection Smell: Static dependency
Static dependencies are hard-to-control dependencies
classBlockCipher
{
publicstaticfunctionfactory($adapter,$options=array())
{
$plugins=static::getSymmetricPluginManager();
$adapter=$plugins->get($adapter,(array)$options);
returnnewstatic($adapter);
}
}
PHP
24/44
ZendCrypt
Dependency Injection Smell: Missing dependency auto-recovery
If you have a dependency, act like you are .
publicstaticfunctiongetSymmetricPluginManager()
{
if(static::$symmetricPlugins===null){
static::setSymmetricPluginManager(newSymmetricPluginManager());
}
returnstatic::$symmetricPlugins;
}
PHP
25/44
ZendCrypt
Dependency Injection Smell: Hidden dependencies
If you have a dependency, make it explicit.
classSymmetricPluginManagerextendsAbstractPluginManager
{
protected$invokableClasses=array(
'mcrypt'=>'ZendCryptSymmetricMcrypt',
);
}
PHP
26/44
ZendCrypt
Suggested refactoring
useZendCryptSymmetricMcrypt;
useZendCryptSymmetricBlockCipher;
$cipher=newMcrypt(array('algo'=>'aes'));
$blockCipher=newBlockCipher($cipher);
PHP
No SymmetricPluginManager
No factory()method
·
·
27/44
ZendCrypt
Dependency Injection Smell: Creation logic reduction
Make way for complex creation logic (and don't think the newoperator will
suffice).
publicstaticfunctionsetSymmetricPluginManager($plugins)
{
if(is_string($plugins)){
$plugins=new$plugins();
}
if(!$pluginsinstanceofSymmetricPluginManager){
thrownewExceptionInvalidArgumentException();
}
static::$symmetricPlugins=$plugins;
}
PHP
28/44
Code review
SymfonyBundleFrameworkBundle
SymfonyBundleFrameworkBundle
HttpCache
abstractclassHttpCacheextendsBaseHttpCache
{
publicfunction__construct(HttpKernelInterface$kernel,$cacheDir=null)
{
$this->kernel=$kernel;
$this->cacheDir=$cacheDir;
parent::__construct(
$kernel,
$this->createStore(),
$this->createEsi(),
array_merge(
array('debug'=>$kernel->isDebug()),
$this->getOptions())
);
}
}
PHP
30/44
SymfonyBundleFrameworkBundle
Dependency Injection Smell: Factory methods
Don't require developers to use inheritance for replacing dependencies.
abstractclassHttpCacheextendsBaseHttpCache
{
protectedfunctioncreateEsi()
{
returnnewEsi();
}
protectedfunctioncreateStore()
{
returnnewStore($this->cacheDir?:$this->kernel->getCacheDir().'/http_cache');
}
}
PHP
31/44
SymfonyBundleFrameworkBundle
Dependency Injection Smell: Programming against an implementation
HttpCachehas a dependency on HttpKernelInterface...
abstractclassHttpCacheextendsBaseHttpCache
{
publicfunction__construct(HttpKernelInterface$kernel,$cacheDir=null)
{
...
}
}
PHP
interfaceHttpKernelInterface
{
publicfunctionhandle(Request$request,$type=self::MASTER_REQUEST,$catch=true);
}
PHP
32/44
SymfonyBundleFrameworkBundle
Dependency Injection Smell: Programming against an implementation
... but it uses of the interface methods
array('debug'=>$kernel->isDebug()), PHP
returnnewStore($this->cacheDir?:$this->kernel->getCacheDir().'/http_cache'); PHP
$this->getKernel()->boot(); PHP
33/44
SymfonyBundleFrameworkBundle
Suggested refactoring
Program against an interface (strictly)
Or: program against an implementation (and type-hint accordingly)
Or: expand the interface to contain the methods you need
·
·
·
34/44
Code review
DoctrineDBAL
DoctrineDBAL
Dependency Injection Smell: Dependencies prohibited
abstractclassType
{
publicstaticfunctionaddType($name,$className)
{
self::$typesMap[$name]=$className;
}
publicstaticfunctiongetType($name)
{
if(!isset(self::$typeObjects[$name])){
self::$typeObjects[$name]=newself::$typesMap[$name]();
}
returnself::$typeObjects[$name];
}
}
Type::getType('datetime')->convertToPHPValue('2013-06-08');
PHP
36/44
DoctrineDBAL
Dependency Injection Smell: Dependencies prohibited
classEncryptedStringTypeextendsType
{
publicfunction__construct(BlockCipher$blockCipher)
{
$this->blockCipher=$blockCipher;
}
publicfunctionconvertToDatabaseValue($value)
{
return$this->blockCipher->encrypt($value);
}
publicfunctionconvertToPHPValue($value)
{
return$this->blockCipher->decrypt($value);
}
}
PHP
37/44
DoctrineDBAL
Dependency Injection Smell: Dependencies prohibited
We can not override Type::__construct()since it is final.
Don't neglect other classes' needs (even if your class has everything it needs)
Type::addType('encrypted_string','EncryptedStringType'); PHP
abstractclassType
{
finalprivatefunction__construct(){}
}
PHP
38/44
DoctrineDBAL
Dependency Injection Smell: Dependencies prohibited
Work-around: static dependency
classEncryptedStringType
{
publicstatic$blockCiper;
}
EncryptedStringType::$blockCipher=...;
PHP
39/44
DoctrineDBAL
Recommended refactoring
1. Split the Typeclass into an AbstractTypeand a TypeRegistry.
2. Set a type instance, instead of just a class.
$blockCipher=...;//ha,weknowhowtomakeone!
$typeRegistry=newTypeRegistry();
$encryptedStringType=newEncryptedStringType($blockCipher);
$typeRegistry->setType('encrypted_string',$encryptedStringType);
PHP
40/44
In conclusion
Good API design
Dependency injection smells
Static dependency
Missing dependency auto-recovery
Hidden dependencies
Creation logic reduction
Factory methods
Programming against an implementation
Dependencies prohibited
·
·
·
·
·
·
·
42/44
Keep in mind...
Be clear and open about what your dependencies are
Require only a minimum amount of dependencies
Develop with your users (other developers) in mind
·
·
·
43/44
Thank you
Please leave some feedback at joind.in/8447
twitter @matthiasnoback
www php-and-symfony.matthiasnoback.nl
github github.com/matthiasnoback
leanpub leanpub.com/a-year-with-symfony

More Related Content

PDF
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
PDF
Who killed object oriented design?
Amir Barylko
 
PDF
Design Patterns in PHP5
Wildan Maulana
 
PDF
What's new with PHP7
SWIFTotter Solutions
 
PPTX
PHP 7 Crash Course
Colin O'Dell
 
PPTX
Domain Driven Design using Laravel
wajrcs
 
PDF
Frontin like-a-backer
Frank de Jonge
 
PDF
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty
 
PHP: 4 Design Patterns to Make Better Code
SWIFTotter Solutions
 
Who killed object oriented design?
Amir Barylko
 
Design Patterns in PHP5
Wildan Maulana
 
What's new with PHP7
SWIFTotter Solutions
 
PHP 7 Crash Course
Colin O'Dell
 
Domain Driven Design using Laravel
wajrcs
 
Frontin like-a-backer
Frank de Jonge
 
Building a Pyramid: Symfony Testing Strategies
CiaranMcNulty
 

What's hot (19)

PDF
Design patterns in PHP
Jason Straughan
 
PDF
Introduction to hexagonal architecture
Manel Sellés
 
PDF
Laravel 5.2 Gates, AuthServiceProvider and Policies
Alison Gianotto
 
PPTX
Dependency injection - the right way
Thibaud Desodt
 
ODP
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
PDF
PHPSpec BDD Framework
Marcello Duarte
 
PDF
Dependency Injection
Alena Holligan
 
PDF
Object Oriented PHP - PART-2
Jalpesh Vasa
 
KEY
PHP security audits
Damien Seguy
 
PDF
Tech friday 22.01.2016
Poutapilvi Web Design
 
PDF
Asynchronous JS in Odoo
Odoo
 
PDF
Java Script Best Practices
Enrique Juan de Dios
 
PDF
JavaScript 101
ygv2000
 
PDF
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
PPTX
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
ODP
Bring the fun back to java
ciklum_ods
 
KEY
Solid principles
Declan Whelan
 
PPTX
Using of TDD practices for Magento
Ivan Chepurnyi
 
PDF
Why is crud a bad idea - focus on real scenarios
Divante
 
Design patterns in PHP
Jason Straughan
 
Introduction to hexagonal architecture
Manel Sellés
 
Laravel 5.2 Gates, AuthServiceProvider and Policies
Alison Gianotto
 
Dependency injection - the right way
Thibaud Desodt
 
Codebits 2012 - Fast relational web site construction.
Nelson Gomes
 
PHPSpec BDD Framework
Marcello Duarte
 
Dependency Injection
Alena Holligan
 
Object Oriented PHP - PART-2
Jalpesh Vasa
 
PHP security audits
Damien Seguy
 
Tech friday 22.01.2016
Poutapilvi Web Design
 
Asynchronous JS in Odoo
Odoo
 
Java Script Best Practices
Enrique Juan de Dios
 
JavaScript 101
ygv2000
 
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Adding Dependency Injection to Legacy Applications
Sam Hennessy
 
Bring the fun back to java
ciklum_ods
 
Solid principles
Declan Whelan
 
Using of TDD practices for Magento
Ivan Chepurnyi
 
Why is crud a bad idea - focus on real scenarios
Divante
 
Ad

Viewers also liked (10)

PDF
Symfony2 & l'architecture Rest
Ahmed Ghali
 
PDF
Event driven application
Chris Saylor
 
PDF
Etude des Frameworks PHP
JEAN-GUILLAUME DUJARDIN
 
PPTX
Créer une API GraphQL avec Symfony
Sébastien Rosset
 
PPT
Building Single Page Application (SPA) with Symfony2 and AngularJS
Antonio Peric-Mazar
 
PPTX
Introduction au business modèle des applications mobile
Abdelkader Rhouati
 
PPT
Symfony 2 : chapitre 2 - Les vues en Twig
Abdelkader Rhouati
 
PPT
Symfony 2 : chapitre 4 - Les services et les formulaires
Abdelkader Rhouati
 
PPT
Symfony 2 : chapitre 3 - Les modèles en Doctrine 2
Abdelkader Rhouati
 
PPTX
Symfony 2 : chapitre 1 - Présentation Générale
Abdelkader Rhouati
 
Symfony2 & l'architecture Rest
Ahmed Ghali
 
Event driven application
Chris Saylor
 
Etude des Frameworks PHP
JEAN-GUILLAUME DUJARDIN
 
Créer une API GraphQL avec Symfony
Sébastien Rosset
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Antonio Peric-Mazar
 
Introduction au business modèle des applications mobile
Abdelkader Rhouati
 
Symfony 2 : chapitre 2 - Les vues en Twig
Abdelkader Rhouati
 
Symfony 2 : chapitre 4 - Les services et les formulaires
Abdelkader Rhouati
 
Symfony 2 : chapitre 3 - Les modèles en Doctrine 2
Abdelkader Rhouati
 
Symfony 2 : chapitre 1 - Présentation Générale
Abdelkader Rhouati
 
Ad

Similar to Dependency Injection Smells (20)

PDF
Building Testable PHP Applications
chartjes
 
PDF
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 
PDF
Php unit (eng)
Anatoliy Okhotnikov
 
KEY
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
PPTX
Design patterns as power of programing
Lukas Lesniewski
 
PPTX
Introducing PHP Latest Updates
Iftekhar Eather
 
PDF
Dependency injection in Drupal 8
Alexei Gorobets
 
PDF
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 
ODP
The why and how of moving to PHP 5.4/5.5
Wim Godden
 
PDF
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
PPTX
PHP7 Presentation
David Sanchez
 
PDF
Lean Php Presentation
Alan Pinstein
 
PDF
Living With Legacy Code
Rowan Merewood
 
PDF
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
KEY
PHPSpec BDD for PHP
Marcello Duarte
 
PDF
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
GeeksLab Odessa
 
PPT
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
KEY
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
PDF
DDD on example of Symfony (Webcamp Odessa 2014)
Oleg Zinchenko
 
PDF
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 
Building Testable PHP Applications
chartjes
 
Zend Certification PHP 5 Sample Questions
Jagat Kothari
 
Php unit (eng)
Anatoliy Okhotnikov
 
PHPUnit testing to Zend_Test
Michelangelo van Dam
 
Design patterns as power of programing
Lukas Lesniewski
 
Introducing PHP Latest Updates
Iftekhar Eather
 
Dependency injection in Drupal 8
Alexei Gorobets
 
EPHPC Webinar Slides: Unit Testing by Arthur Purnama
Enterprise PHP Center
 
The why and how of moving to PHP 5.4/5.5
Wim Godden
 
Introduction to Unit Testing with PHPUnit
Michelangelo van Dam
 
PHP7 Presentation
David Sanchez
 
Lean Php Presentation
Alan Pinstein
 
Living With Legacy Code
Rowan Merewood
 
10 PHP Design Patterns #burningkeyboards
Denis Ristic
 
PHPSpec BDD for PHP
Marcello Duarte
 
WebCamp: Developer Day: DDD in PHP on example of Symfony - Олег Зинченко
GeeksLab Odessa
 
Zend framework 03 - singleton factory data mapper caching logging
Tricode (part of Dept)
 
Php Unit With Zend Framework Zendcon09
Michelangelo van Dam
 
DDD on example of Symfony (Webcamp Odessa 2014)
Oleg Zinchenko
 
関西PHP勉強会 php5.4つまみぐい
Hisateru Tanaka
 

More from Matthias Noback (20)

PDF
Rector fireside chat - PHPMiNDS meetup
Matthias Noback
 
PDF
Service abstractions - Part 1: Queries
Matthias Noback
 
PDF
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Matthias Noback
 
PDF
Advanced web application architecture - PHP Barcelona
Matthias Noback
 
PDF
A testing strategy for hexagonal applications
Matthias Noback
 
PDF
Advanced web application architecture - Talk
Matthias Noback
 
PDF
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
Matthias Noback
 
PDF
Layers, ports and adapters
Matthias Noback
 
PDF
Beyond design principles and patterns (muCon 2019 edition)
Matthias Noback
 
PDF
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
PDF
Advanced web application architecture Way2Web
Matthias Noback
 
PDF
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
PDF
Beyond Design Principles and Patterns
Matthias Noback
 
PDF
Building Autonomous Services
Matthias Noback
 
PDF
Advanced Application Architecture Symfony Live Berlin 2018
Matthias Noback
 
PDF
Designing for Autonomy
Matthias Noback
 
PDF
Docker workshop
Matthias Noback
 
PDF
Docker swarm workshop
Matthias Noback
 
PDF
Docker compose workshop
Matthias Noback
 
PDF
Building autonomous services
Matthias Noback
 
Rector fireside chat - PHPMiNDS meetup
Matthias Noback
 
Service abstractions - Part 1: Queries
Matthias Noback
 
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Matthias Noback
 
Advanced web application architecture - PHP Barcelona
Matthias Noback
 
A testing strategy for hexagonal applications
Matthias Noback
 
Advanced web application architecture - Talk
Matthias Noback
 
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...
Matthias Noback
 
Layers, ports and adapters
Matthias Noback
 
Beyond design principles and patterns (muCon 2019 edition)
Matthias Noback
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Advanced web application architecture Way2Web
Matthias Noback
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Matthias Noback
 
Beyond Design Principles and Patterns
Matthias Noback
 
Building Autonomous Services
Matthias Noback
 
Advanced Application Architecture Symfony Live Berlin 2018
Matthias Noback
 
Designing for Autonomy
Matthias Noback
 
Docker workshop
Matthias Noback
 
Docker swarm workshop
Matthias Noback
 
Docker compose workshop
Matthias Noback
 
Building autonomous services
Matthias Noback
 

Recently uploaded (20)

PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Doc9.....................................
SofiaCollazos
 
PPTX
The Future of AI & Machine Learning.pptx
pritsen4700
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
The Future of Artificial Intelligence (AI)
Mukul
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Doc9.....................................
SofiaCollazos
 
The Future of AI & Machine Learning.pptx
pritsen4700
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 

Dependency Injection Smells