SlideShare una empresa de Scribd logo
1 de 22
Dependency Injection Integration of Symfony DI Container to  Zend Framework
Who am I ? ,[object Object]
Software Architect at  www.fishpond.co.nz
Technical Director at  www.reddelacosta.com.ar
Consultant at  www.bookfinda.com.au
[object Object],[object Object],Product Service class Cache class Loging class EntityManager class 'Object A' dependends on 'Object B' if 'Object A' needs 'Object B' in order to execute correctly. (Jakob Jenkov)
More dependencies ,[object Object],Product Service class Cache class Loging class EntityManager class DB Writer class Frontend class Backend class Log Writer class As the size of the applications grows, the amount and complexity of dependencies grows as well
Hardcoded Dependencies Make dependencies explicit class ProductService { ... public function __constructor() { $boostrap =  Zend_Controller_Front::getInstance()->getParam('bootstrap'); $this->_cache = $boostrap->getResource('cache'); $this->_logger = $boostrap->getResource('logger'); $this->_entityManager = $boostrap->getResource('entityManager'); } } We have hardcoded dependencies when, the class set its dependencies by itself:
Dependency Injection ? Make dependencies explicit ,[object Object],..... $cache = $boostrap->getResource('cache') $logger = $boostrap->getResource('logger') $entityManager = $boostrap->getResource('entityManager') $productService = new ProductService( $cache, $logger, $entityManager ); Injecting dependencies through the constructor:
New Code... Make dependencies explicit class ProductService { ... public function __constructor($cache, $logger, $entityManager) { $this->_cache = $cache; $this->_logger = $logger; $this->_entityManager = $entityManager; } } Injecting dependencies through the constructor:
Dependency InjectionTypes ,[object Object]
Setter Injection: The dependencies are injected trought setter, this can be good if a large numbers of dependencies are present.
Interface: Components implement specific containers provided by the containers in order to be configured.
Dependency Injection ,[object Object]
When using dependency injection, a consumer component specifies the service contract by interface, and the injector component selects an implementation on behalf of the dependent component. (inversion of control)
In its simplest implementation, code that creates a dependent object supplies dependencies to that object via constructor arguments or by setting properties on the object.
Wikipedia (http://en.wikipedia.org/wiki/Dependency_injection)
Advantages ,[object Object]
Loose Coupling.
More Testable code: Unit test, able to replace for Mocks objects.
Inject different object for different environments (different logger for dev/production).
Since the object creation is handle by a centralized component, we avoid copy paste the same code inside of different objects.

Más contenido relacionado

La actualidad más candente

Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
Stephan Hochdörfer
 

La actualidad más candente (20)

How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Hibernate training
Hibernate trainingHibernate training
Hibernate training
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentesDesign pattern in Symfony2 - Nanos gigantium humeris insidentes
Design pattern in Symfony2 - Nanos gigantium humeris insidentes
 
AspMVC4 start101
AspMVC4 start101AspMVC4 start101
AspMVC4 start101
 
Testing untestable code - phpday
Testing untestable code - phpdayTesting untestable code - phpday
Testing untestable code - phpday
 
Spring training
Spring trainingSpring training
Spring training
 
OAuth 2.0 Threat Landscape
OAuth 2.0 Threat LandscapeOAuth 2.0 Threat Landscape
OAuth 2.0 Threat Landscape
 
Leave your jQuery behind
Leave your jQuery behindLeave your jQuery behind
Leave your jQuery behind
 
Using API Platform to build ticketing system #symfonycon
Using API Platform to build ticketing system #symfonyconUsing API Platform to build ticketing system #symfonycon
Using API Platform to build ticketing system #symfonycon
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)
4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)
4.Spring IoC&DI(Spring Ioc실습_어노테이션 기반)
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Cloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFECloud Native Identity with SPIFFE
Cloud Native Identity with SPIFFE
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
Angular2 Development for Java developers
Angular2 Development for Java developersAngular2 Development for Java developers
Angular2 Development for Java developers
 
Code Generation idioms with Xtend
Code Generation idioms with XtendCode Generation idioms with Xtend
Code Generation idioms with Xtend
 
Using API platform to build ticketing system (translations, time zones, ...) ...
Using API platform to build ticketing system (translations, time zones, ...) ...Using API platform to build ticketing system (translations, time zones, ...) ...
Using API platform to build ticketing system (translations, time zones, ...) ...
 
Java Enterprise Edition
Java Enterprise EditionJava Enterprise Edition
Java Enterprise Edition
 

Similar a Dependency Injection, Zend Framework and Symfony Container

Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
Stephan Hochdörfer
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJava Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily Jiang
JAX London
 

Similar a Dependency Injection, Zend Framework and Symfony Container (20)

JavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In DepthJavaOne 2009 BOF-5189 Griffon In Depth
JavaOne 2009 BOF-5189 Griffon In Depth
 
The Web on OSGi: Here's How
The Web on OSGi: Here's HowThe Web on OSGi: Here's How
The Web on OSGi: Here's How
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...
 
Os Johnson
Os JohnsonOs Johnson
Os Johnson
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily JiangJava Tech & Tools | OSGi Best Practices | Emily Jiang
Java Tech & Tools | OSGi Best Practices | Emily Jiang
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi style
 
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
Kicking off with Zend Expressive and Doctrine ORM (PHP Srbija 2017)
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Android architecture
Android architecture Android architecture
Android architecture
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Building Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in RailsBuilding Mobile Friendly APIs in Rails
Building Mobile Friendly APIs in Rails
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaver
 
OpenWebBeans/Web Beans
OpenWebBeans/Web BeansOpenWebBeans/Web Beans
OpenWebBeans/Web Beans
 
Jdbc
JdbcJdbc
Jdbc
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

Dependency Injection, Zend Framework and Symfony Container

  • 1. Dependency Injection Integration of Symfony DI Container to Zend Framework
  • 2.
  • 3. Software Architect at www.fishpond.co.nz
  • 4. Technical Director at www.reddelacosta.com.ar
  • 5. Consultant at www.bookfinda.com.au
  • 6.
  • 7.
  • 8. Hardcoded Dependencies Make dependencies explicit class ProductService { ... public function __constructor() { $boostrap = Zend_Controller_Front::getInstance()->getParam('bootstrap'); $this->_cache = $boostrap->getResource('cache'); $this->_logger = $boostrap->getResource('logger'); $this->_entityManager = $boostrap->getResource('entityManager'); } } We have hardcoded dependencies when, the class set its dependencies by itself:
  • 9.
  • 10. New Code... Make dependencies explicit class ProductService { ... public function __constructor($cache, $logger, $entityManager) { $this->_cache = $cache; $this->_logger = $logger; $this->_entityManager = $entityManager; } } Injecting dependencies through the constructor:
  • 11.
  • 12. Setter Injection: The dependencies are injected trought setter, this can be good if a large numbers of dependencies are present.
  • 13. Interface: Components implement specific containers provided by the containers in order to be configured.
  • 14.
  • 15. When using dependency injection, a consumer component specifies the service contract by interface, and the injector component selects an implementation on behalf of the dependent component. (inversion of control)
  • 16. In its simplest implementation, code that creates a dependent object supplies dependencies to that object via constructor arguments or by setting properties on the object.
  • 18.
  • 20. More Testable code: Unit test, able to replace for Mocks objects.
  • 21. Inject different object for different environments (different logger for dev/production).
  • 22. Since the object creation is handle by a centralized component, we avoid copy paste the same code inside of different objects.
  • 23. Dependency Injection Container DI container The Container knows: - How the create new objects. - Classes Dependencies. Cache Logger EManager ProductService Cache Logger Event Manager An object and its dependencies can be created and initialized by a ”Dependency - Injection Container”.
  • 24.
  • 25. Pico
  • 26. Butterfly Java example using anotations: @Component public class SomeClass { @Autowired(required=true) public SomeClass(OtherClass bean1, OtherClass bean2) { ... } }
  • 27.
  • 28. Written by Fabien Potencier, stand alone library http://components.symfony-project.org/ stable version
  • 29. Zend Framework 2 DI Component (Beta 1)
  • 30. Not ready yet, but promising.
  • 31.
  • 32. Creating the Container (Boostraping) from http://components.symfony-project.org/ require_once '/PATH/TO/sfServiceContainerAutoloader.php'; sfServiceContainerAutoloader::register(); $sc = new sfServiceContainerBuilder(); $loader = new sfServiceContainerLoaderFileXml($sc); $loader->load('/somewhere/container.xml'); $sc->ipManager From http://components.symfony-project.org/dependency-injection/trunk/book/05-Service-Description
  • 33. Service Definition (XML format) from http://components.symfony-project.org/ <service id=&quot;ipManager&quot; class=&quot;MyLib _Gearman_Client_Competitor_IpManager&quot; > <argument type=&quot;service&quot; id=&quot;documentManager&quot;/> <argument type=&quot;service&quot; id=&quot;gearmanClient&quot;/> <argument type=&quot;service&quot; id=&quot;ipmanager.logger&quot;/> </service> <service id=&quot;ipmanager.logger&quot; class=&quot;MyLib_Log&quot; constructor=&quot;getInstance&quot;> <call method=&quot;addWriter&quot;> <argument type=&quot;service&quot;> <service class=&quot;Zend_Log_Writer_Stream&quot;> <argument>php://output</argument> </service> </argument> </call> <call method=&quot;addWriter&quot;> <argument type=&quot;service&quot;> <service class=&quot;Zend_Log_Writer_Stream&quot;> <argument>%ipmanager.loger.file%</argument> </service> </argument> </call> </service> .... ....
  • 34. Need for Speed from http://components.symfony-project.org/ ..... $phpCointernerClassCode = $dumper->dump(array('class' => 'Container')); file_put_contents('/somewhere/container.php', $code); Symfony DI compoment has a mechanism where optimized 'plain' php container classes can be Generated from configuration. Once generated those containers classes can be used avoiding parsing configuration files every time.
  • 35. Need for Speed from http://components.symfony-project.org/ class SymfonyContainerDev extends sfServiceContainer { protected function getLogerService() { if (isset($this->shared['loger'])) return $this->shared['loger']; $instance = call_user_func(array('MyLib_Log', 'getResource')); return $this->shared['loger'] = $instance; } protected function getIpManagerService() { if (isset($this->shared['ipManager'])) return $this->shared['ipManager']; $instance = new Fishpond_Gearman_Client_Competitor_IpManager( $this->getService('documentManager'), $this->getService('gearmanClient'), $this->getService('ipmanager.logger')); return $this->shared['ipManager'] = $instance; } ...... ..... } The Container Builder use the configuration to create a php container class that is able to create an inject dependencies. The Container class created it is optimized for speed and don't have any overhead (parsing configuration files, etc).
  • 36.
  • 37. Note: Production and development in this example use diferent xml files, in this way we can use different definitions for diffrent enviroments.
  • 38.
  • 40.