pastebin

Paste Search Dynamic
Recent pastes
Container dynamic
  1. <?php
  2.  
  3. /**
  4.  * Test: NetteDIContainer dynamic usage.
  5.  *
  6.  * @author     David Grudl
  7.  * @package    NetteDI
  8.  * @subpackage UnitTests
  9.  */
  10.  
  11. use NetteDIContainer;
  12.  
  13.  
  14.  
  15. require __DIR__ . '/../bootstrap.php';
  16.  
  17.  
  18.  
  19. class Service
  20. {
  21. }
  22.  
  23. $one = new Service;
  24. $two = new Service;
  25.  
  26.  
  27. $container = new Container;
  28. $container->addService('one', $one);
  29. $container->addService('two', $two);
  30.  
  31. assert::true( $container->hasService('one') );
  32. assert::true( $container->isCreated('one') );
  33. assert::true( $container->hasService('two') );
  34. assert::false( $container->hasService('undefined') );
  35.  
  36. assert::same( $one, $container->getService('one') );
  37. assert::same( $two, $container->getService('two') );
  38.  
  39.  
  40. // class name
  41. $builder = $container->addService('three', 'Service');
  42.  
  43. assert::true( $container->hasService('three') );
  44. assert::true( $container->getService('three') instanceof Service );
  45. assert::same( $container->getService('three'), $container->getService('three') ); // shared
  46.  
  47.  
  48. // factory
  49. $container->addService('four', function($container){
  50.         assert::true( $container instanceof Container );
  51.         return new Service;
  52. });
  53.  
  54. assert::true( $container->hasService('four') );
  55. assert::false( $container->isCreated('four') );
  56. assert::true( $container->getService('four') instanceof Service );
  57. assert::true( $container->isCreated('four') );
  58. assert::same( $container->getService('four'), $container->getService('four') ); // shared
  59.  
  60.  
  61. // bad factory
  62. try {
  63.         $container->addService('five', function($container){});
  64.         $container->getService('five');
  65.         assert::fail('Expected exception');
  66. } catch (Exception $e) {
  67.         assert::exception('NetteUnexpectedValueException', "Unable to create service 'five', value returned by factory '%a%' is not object.", $e );
  68. }
Parsed in 0.113 seconds