Dependency Injection Containers  Įžanga                      Dependency Injection Containers                              ...
Dependency Injection Containers  ĮžangaKas aš toks?               Povilas Balzaravičius               @Pawka              ...
Dependency Injection Containers  Dependency Injection     Kas yra Dependency Injection?        Kas yra Dependency Injection?
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Kuo blogas šis kodas?  1     class...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Kuo blogas šis kodas?  1     class...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Ar dabar geriau?  1     class Feed...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Ar dabar geriau?  1     class Feed...
Dependency Injection Containers  Dependency Injection     Kas yra Dependency Injection?Ką daryti?           Iškelti vidini...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Kodėl šis kodas geresnis?  1     n...
Dependency Injection Containers  Dependency Injection     Kas yra Dependency Injection?Sveiki, aš DI                      ...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?Objektų kūrimas       DI naudojimu...
Dependency Injection Containers  Dependency Injection     Kas yra Dependency Injection?Kas yra DI?               Projektav...
Dependency Injection Containers  Dependency Injection      Kas yra Dependency Injection?DI būdai  1     $feed = new Feed("...
Dependency Injection Containers  DIC bibliotekos                                    Kam kurti savo jei yra..              ...
Dependency Injection Containers  DIC bibliotekosReikalavimai DI konteineriui                Turi veikti greitai.          ...
Dependency Injection Containers  DIC bibliotekos     Pimple                                  Pimple
Dependency Injection Containers  DIC bibliotekos     PimplePimple       A simple Dependency Injection Container for PHP 5....
Dependency Injection Containers  DIC bibliotekos      PimpleDarbas su objektais  1     $container = new Pimple();  2     /...
Dependency Injection Containers  DIC bibliotekos      PimpleIšskaidymas į modulius  1     class FeedContainer extends Pimp...
Dependency Injection Containers  DIC bibliotekos      PimpleIšskaidymas į modulius  1     class GlobalContainer extends Pi...
Dependency Injection Containers  DIC bibliotekos     PimpleSparta       Konteinerio kūrimas        ./run-tests.sh        P...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection Component        Symfony Dependency Inje...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection ComponentSymfony DIC               Symfo...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection ComponentPalaikomi formatai       Prikal...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentNaudojimas: PHP  1     use Sym...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentNaudojimas: XML  1     <parame...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentNaudojimas: YAML  1     parame...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentDI perdengimas               P...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection ComponentKompiliavimas                Ko...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection ComponentSukompiliuoto rezultato saugoji...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentSukompiliuoto rezultato saugoj...
Dependency Injection Containers  DIC bibliotekos     Symfony Dependency Injection ComponentTagged servisai               T...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentTagged servisai       Modifikuo...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentTagged servisai       Turim ap...
Dependency Injection Containers  DIC bibliotekos      Symfony Dependency Injection ComponentTagged servisai  1     use Sym...
Dependency Injection Containers  Pabaiga     IšvadosIšvados               Norint pradėti naudoti DI, neprivaloma naudoti t...
Dependency Injection Containers  Pabaiga     ResursaiResursai                Symfony Dependency Injection component docs: ...
Dependency Injection Containers  Pabaiga     Resursai                                        Ačiū                         ...
Upcoming SlideShare
Loading in …5
×

Dependency Injection Containers

1,320 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,320
On SlideShare
0
From Embeds
0
Number of Embeds
433
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Dependency Injection Containers

  1. 1. Dependency Injection Containers Įžanga Dependency Injection Containers VilniusPHP Susitikimas #3 Povilas Balzaravičius 2013 m. vasario 7 d.
  2. 2. Dependency Injection Containers ĮžangaKas aš toks? Povilas Balzaravičius @Pawka github.com/pawka linkedin.com/in/pawka pawka.linija.net
  3. 3. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection? Kas yra Dependency Injection?
  4. 4. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Kuo blogas šis kodas? 1 class FeedGenerator { 2 3 protected $feed; 4 5 public function __construct() { 6 // Create feed every 6 hours. 7 $this->feed = new SomeFeed(’0 */6 * * *’); 8 } 9 } 10 //.. 11 $generator = new FeedGenerator;
  5. 5. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Kuo blogas šis kodas? 1 class FeedGenerator { 2 3 protected $feed; 4 5 public function __construct() { 6 // Create feed every 6 hours. 7 $this->feed = new SomeFeed(’0 */6 * * *’); 8 } 9 } 10 //.. 11 $generator = new FeedGenerator; 1 Sudėtinga parašyti testą. 2 Gali tekti keisti kodą modifikuojant Feed klasę. 3 Teks modifikuoti FeedGenerator klasę, norint pakeisti SomeFeed vykdymo intervalą.
  6. 6. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Ar dabar geriau? 1 class FeedGenerator { 2 3 protected $feed; 4 5 public function __construct($interval) { 6 $this->feed = new SomeFeed($interval); 7 } 8 } 9 //.. 10 $generator = new FeedGenerator(’0 */6 * * *’);
  7. 7. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Ar dabar geriau? 1 class FeedGenerator { 2 3 protected $feed; 4 5 public function __construct($interval) { 6 $this->feed = new SomeFeed($interval); 7 } 8 } 9 //.. 10 $generator = new FeedGenerator(’0 */6 * * *’); 1 Sudėtinga parašyti testą. 2 Gali tekti keisti kodą modifikuojant Feed klasę. 3 SomeFeed klasė vis dar priklausoma nuo FeedGenerator.
  8. 8. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Ką daryti? Iškelti vidinių objektų kūrimą už klasės ribų!
  9. 9. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Kodėl šis kodas geresnis? 1 namespace Feed; 2 3 class FeedGenerator { 4 5 protected $feed; 6 7 public function __construct(FeedInterface $feed) { 8 $this->feed = $feed; 9 } 10 } 11 //.. 12 $feed = new SomeFeed(’0 */6 * * *’); 13 $generator = new FeedGenerator($feed); 1 Patogu rašyti testus (vietoj Feed galima paduoti mock objektą). 2 $feed objektas nepriklauso nuo FeedGenerator klasės. 3 Modifikuojant FeedInterface klases, nereikės keisti FeedGenerator kodo.
  10. 10. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Sveiki, aš DI Štai Jums Dependency Injection!
  11. 11. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Objektų kūrimas DI naudojimui konteineris nereikalingas. 1 $config = new DoctrineDBALConfiguration(); 2 $connectionParams = array( 3 ’dbname’ => ’mydb’, 4 ’user’ => ’user’, 5 ’password’ => ’secret’, 6 ’host’ => ’localhost’, 7 ’driver’ => ’pdo_mysql’, 8 ); 9 $conn = DoctrineDBALDriverManager::getConnection( 10 $connectionParams, $config); 11 $productService = new Product($conn); 12 $interval = "0 */6 * * *"; 13 $feed = new FeedSomeFeed($interval); 14 $feed->setProductService($productService); 15 $feedGenerator = new FeedFeedGenerator($feed); 16 //Maybe add objects to some registry. 17 //..
  12. 12. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?Kas yra DI? Projektavimo šablonas (design pattern). Aktualus tik objektiniame programavime. Atskiria komponentus (decoupling). Standartizuoja ir suteikia galimybę centralizuoti objektų kūrimą Jūsų sistemoje.
  13. 13. Dependency Injection Containers Dependency Injection Kas yra Dependency Injection?DI būdai 1 $feed = new Feed("0 */6 * * *"); 2 3 //Konstruktorius 4 $generator = new FeedGenerator($feed); 5 6 //Metodas (setter) 7 $generator = new FeedGenerator; 8 $generator->setFeed($feed); 9 10 //Atributas 11 $generator = new FeedGenerator; 12 $generator->feed = $feed;
  14. 14. Dependency Injection Containers DIC bibliotekos Kam kurti savo jei yra.. DIC bibliotekos
  15. 15. Dependency Injection Containers DIC bibliotekosReikalavimai DI konteineriui Turi veikti greitai. Privalo dirbti su bet kokiu PHP objektu. Objektai neturi žinoti apie DI konteinerį. Nekurti objekto jei jis jau sukurtas.1 1 Kai to reikia.
  16. 16. Dependency Injection Containers DIC bibliotekos Pimple Pimple
  17. 17. Dependency Injection Containers DIC bibliotekos PimplePimple A simple Dependency Injection Container for PHP 5.3. Autorius: Fabien Potencier pimple.sensiolabs.org Paprastas. Greitas. Integravimas - kelios eilutės.
  18. 18. Dependency Injection Containers DIC bibliotekos PimpleDarbas su objektais 1 $container = new Pimple(); 2 // .. 3 4 $container[’feed.somefeed.interval’] = ’0 */6 * * *’; 5 $container[’feed.somefeed.class’] = ’FeedSomeFeed’; 6 7 $container[’feed.somefeed’] = function($c) { 8 return new $c[’feed.somefeed.class’]( 9 $c[’feed.somefeed.interval’] 10 ); 11 }; 12 13 //Lazy loading 14 $container[’feed.generator.class’] = ’FeedFeedGenerator’; 15 $container[’feed.generator’] = $container->share(function($c) { 16 return new $c[’feed.generator.class’]($c[’feed.somefeed’]); 17 }); 18 19 // .. 20 $manager = $container[’feed.generator’];
  19. 19. Dependency Injection Containers DIC bibliotekos PimpleIšskaidymas į modulius 1 class FeedContainer extends Pimple { 2 3 public function __construct() { 4 $this[’feed.somefeed.interval’] = ’0 */6 * * *’; 5 $this[’feed.somefeed.class’] = ’FeedSomeFeed’; 6 7 $this[’feed.somefeed’] = function($c) { 8 return new $c[’feed.somefeed.class’]( 9 $c[’feed.somefeed.interval’] 10 ); 11 }; 12 13 $this[’feed.generator.class’] = ’FeedFeedGenerator’; 14 $this[’feed.generator’] = $this->share(function($c) { 15 return new $c[’feed.generator.class’]($c[’feed.somefeed’]); 16 }); 17 } 18 }
  20. 20. Dependency Injection Containers DIC bibliotekos PimpleIšskaidymas į modulius 1 class GlobalContainer extends Pimple { 2 3 public function __construct() { 4 $this[’feeds’] = $this->share(function($c) { 5 return new FeedContainer; 6 }; 7 } 8 } 9 10 //.. 11 $container = new GlobalContainer; 12 //Change value 13 $container[’feeds’][’feed.somefeed.interval’] = ’0 */12 * * *’; 14 $generator = $container[’feeds’][’feed.generator’];
  21. 21. Dependency Injection Containers DIC bibliotekos PimpleSparta Konteinerio kūrimas ./run-tests.sh Pimple 265K 579K 0.00086s DependencyInjection 267K 931K 0.006124s DependencyInjection (dumped) 688K 738K 0.000495s Šaltinis: https://gist.github.com/igorw/3833123
  22. 22. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection Component Symfony Dependency Injection Component
  23. 23. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentSymfony DIC Symfony komponentas. http://symfony.com/components Daug galimybių. Greitas (teisingai naudojant). Pagal nutylėjimą naudojamas Symfony2 karkase.
  24. 24. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentPalaikomi formatai Prikalusomybes galima aprašyti šiais formatais: PHP XML YAML INI (Palaiko tik parametrų aprašymus).
  25. 25. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentNaudojimas: PHP 1 use SymfonyComponentDependencyInjectionContainerBuilder; 2 use SymfonyComponentDependencyInjectionReference; 3 4 $container = new ContainerBuilder(); 5 6 $container->setParameter(’feed.somefeed.interval’, ’0 */6 * * *’); 7 $container 8 ->register(’feed.somefeed’, ’SomeFeed’) 9 ->addArgument(’%feed.somefeed.interval%’); 10 11 $container 12 ->register(’feed.generator’, ’FeedGenerator’) 13 ->addArgument(new Reference(’feed.somefeed’));
  26. 26. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentNaudojimas: XML 1 <parameters> 2 <parameter key="feed.somefeed.interval">0 */6 * * *</parameter> 3 </parameters> 4 5 <services> 6 <service id="feed.somefeed" class="SomeFeed"> 7 <argument>%feed.somefeed.interval%</argument> 8 </service> 9 10 <service id="feed.generator" class="FeedGenerator"> 11 <argument type="service" id="feed.somefeed" /> 12 </service> 13 </services>
  27. 27. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentNaudojimas: YAML 1 parameters: 2 # ... 3 feed.somefeed.interval: 0 */6 * * * 4 5 services: 6 feed.somefeed: 7 class: SomeFeed 8 arguments: [ % feed.somefeed.interval%] 9 feed.generator: 10 class: FeedGenerator 11 arguments: [ @ feed.somefeed]
  28. 28. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentDI perdengimas Palaiko YAML ir XML formatai. Leidžia perdengti anksčiau aprašytas DI priklausomybes (pvz. dirbant su Symfony2). Patogu naudoti skirtingas konfigūracijas: test, dev, live. 1 use SymfonyComponentDependencyInjectionContainerBuilder; 2 use SymfonyComponentConfigFileLocator; 3 use SymfonyComponentDependencyInjectionLoaderXmlFileLoader; 4 5 $container = new ContainerBuilder(); 6 $loader = new XmlFileLoader($container, new FileLocator(__DIR__)); 7 $loader->load(’services.xml’);
  29. 29. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentKompiliavimas Konteineris gali būti kompiliuojamas. 1 $container->compile(); Aptinkamos klaidos: Neegzistuojančios priklausomybės. Ciklinės priklausomybės. Atliekama optimizacija. Sukompiliuotas rezultatas gali būti saugomas į diską ir naudojamas kaip cache’as.2 P.S. Symfony2 tuo rūpinasi pagal nutylėjimą :-) 2 Pamenat spartos palyginimo rezultatus?
  30. 30. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentSukompiliuoto rezultato saugojimas į diską Naudojamos Dumper klasės. Galima konvertuoti iš vieno formato į kitą. Palaikomi formatai: PHP XML YAML GraphWiz (www.graphwiz.org)
  31. 31. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentSukompiliuoto rezultato saugojimas į diską 1 use SymfonyComponentDependencyInjectionContainerBuilder; 2 use SymfonyComponentDependencyInjectionDumperPhpDumper; 3 4 $file = __DIR__ .’/cache/container.php’; 5 6 if (file_exists($file)) { 7 require_once $file; 8 $container = new ProjectServiceContainer(); 9 } else { 10 $container = new ContainerBuilder(); 11 // ... 12 $container->compile(); 13 14 $dumper = new PhpDumper($container); 15 file_put_contents($file, $dumper->dump()); 16 } ProjectServiceContainer - pavadinimas pagal nutylėjimą.
  32. 32. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentTagged servisai Tag - atributas, žymintis panašius objektus. Leidžia vykdyti analogiškus veiksmus visiems pažymėtiems objektams.
  33. 33. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentTagged servisai Modifikuojam FeedGenerator klasę, pridėdami kelių Feed objektų palaikymą: 1 class FeedGenerator { 2 3 protected $feeds = array(); 4 5 public function __construct() { 6 } 7 8 public function addFeed(FeedInterface $feed) { 9 $this->feeds[] = $feed; 10 } 11 }
  34. 34. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentTagged servisai Turim aprašytas kelias skirtingas Feed klases. 1 <parameters> 2 <parameter key="feed.somefeed.interval">0 */6 * * *</parameter> 3 <parameter key="feed.otherfeed.interval">0 */12 * * *</parameter> 4 </parameters> 5 6 <services> 7 <service id="feed.somefeed" class="SomeFeed"> 8 <argument>%feed.somefeed.interval%</argument> 9 <tag name="feed" /> 10 </service> 11 <service id="feed.otherfeed" class="OtherFeed"> 12 <argument>%feed.otherfeed.interval%</argument> 13 <tag name="feed" /> 14 </service> 15 16 <service id="feed.generator" class="FeedGenerator" /> 17 </services>
  35. 35. Dependency Injection Containers DIC bibliotekos Symfony Dependency Injection ComponentTagged servisai 1 use SymfonyComponentDependencyInjectionContainerBuilder; 2 use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface; 3 use SymfonyComponentDependencyInjectionReference; 4 5 class FeedCompilerPass implements CompilerPassInterface 6 { 7 public function process(ContainerBuilder $container) 8 { 9 if (!$container->hasDefinition(’feed.generator’)) { 10 return; 11 } 12 13 $definition = $container->getDefinition(’feed.generator’); 14 $taggedServices = $container->findTaggedServiceIds(’feed’); 15 foreach ($taggedServices as $id => $attributes) { 16 $definition->addMethodCall(’addFeed’, 17 array(new Reference($id))); 18 } 19 } 20 }
  36. 36. Dependency Injection Containers Pabaiga IšvadosIšvados Norint pradėti naudoti DI, neprivaloma naudoti tam skirtos bibliotekos. DI verčia kodą rašyti teisingai. Paprasčiau atlikti pakeitimus. Paprasčiau (įmanoma?) rašyti testus. Ar verta DI naudoti egzistuojančiuose projektuose? TAIP (žr. aukščiau esančius punktus).
  37. 37. Dependency Injection Containers Pabaiga ResursaiResursai Symfony Dependency Injection component docs: http://symfony.com/doc/current/components/ dependency_injection/ Fabien Potencier blog: What is dependency injection? http://fabien.potencier.org/article/11/ what-is-dependency-injection Inversion of Control Containers and the Dependency Injection pattern: http://www.martinfowler.com/ articles/injection.html Zend DI: https: //packages.zendframework.com/docs/latest/ manual/en/modules/zend.di.introduction.html
  38. 38. Dependency Injection Containers Pabaiga Resursai Ačiū Atsiliepimai: https://joind.in/8105

×