PHP code example of phoole / di

1. Go to this page and download the library: Download phoole/di library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phoole / di example snippets


  use Phoole\Di\Container;
  use Phoole\Config\Config;
  use Phoole\Cache\Cache;
  use Phoole\Cache\Adaptor\FileAdaptor;

  $configData = [
      // service definitions
      'di.service' => [
          // classname & constructor arguments
          'cache'  => [
              'class' => Cache::class,
              'args' => ['${#cacheDriver}'] // optional
          ],

          // use classname directly
          'cacheDriver' => FileAdaptor::class
      ],

      // methods to run after each object initiation
      'di.after' => [
          // a callable, takes THE object as parameter
          function($obj) { echo "ok"; },
  
          // will be converted to $obj->setLogger($logger)
          'setLogger',
      ]
  ];

  // inject configurations into container
  $container = new Container(new Config($configData));

  // get service by id 'cache' (di.service.cache)
  $cache = $container->get('cache');
  

    $config = [
        ...
        // use predefined 'sytem.tmpdir' in arguments etc.
        'di.service.cacheDriver' => [
            'class' => FileAdaptor::class,
            'args'  => ['${system.tmpdir}'],
        ],
        ...
    ];
    

    $configData = [
      ...
      'di.service' => [
          'cache'  => [
              'class' => Cache::class,
              'args' => ['${#cacheDriver}'] // object reference
          ],
          'cacheDriver' => ...
      ...
    

    $confData = [
        // methods executed after ALL object initiation
        'di.after' => [
            [['${#logger}', 'notice'], ['object created using ${log.facility}']]
        ]
    ];
    

    $config = [
       'di.service' => [
           ...
           'cache', [
               'class'  => '${cache.class}',
               'args'   => ['${#cachedriver}'], // constructor arguments
               'before' => [
                   [['${#logger}', 'info'], ['before initiating cache']], // $logger->info(...)
               ],
               'after'  => [
                   'clearCache', // $cache->clearCache() method
                   ['setLogger', ['${#logger}']], // $cache->setLogger($logger), argument is optional
                   [['${#logger}', 'info'], ['just a info']], // $logger->info(...)
                   function($cache) { // a callable takes object in parameter

                   }, 
               ]
           ],
           ...
       ]
    ];
    

      ...
        'after' => [
            // $obj->setLogger($logger), $logger will be injected automatically
            'setLogger', // object implementing 'LoggerAwareInterface'
        ],
      ...
      

       ...
         'after' => [
             // callable takes initiated object as parameter
             function($obj) {
             },
         ],
       ...
      

       ...
         'after' => [
             // a pseudo callable with references
             [['${#logger}', 'info'], ['just a info']], // $logger->info(...)
         ],
       ...
      

    $configData = [
        // before all instances initiated
        'di.before' => [
            [['${#logger}', 'info'], ['before create']],
        ],
        // after methods for all instances
        'di.after' => [
            ['setLogger', ['${#logger}']], // arguments are optional
            'setDispatcher',  // simple enough, set event dispatcher
        ],
    ];
    

    // cache service by default is in shared scope
    $cache1 = $container->get('cache');

    // get again
    $cache2 = $container->get('cache');

    // same
    var_dump($cache1 === $cache2); // true

    // get a NEW cache instance
    $cache3 = $container->get('cache@');

    // different instances
    var_dump($cache1 !== $cache3); // true

    // but both share the same cacheDriver dependent service
    var_dump($cache1->getAdaptor() === $cache3->getAdaptor()); // true
    

    // no scope
    $cache1 = $container->get('cache');

    // in `myScope`
    $cache2 = $container->get('cache@myScope');

    // different instances
    var_dump($cache1 !== $cache2); // true

    // shared in myScope
    $cache3 = $container->get('cache@myScope');
    var_dump($cache2 === $cache2); // true
    

    $container->set('cache', [
        'class' => Cache::class,
        'args'  => ['${#driver@myScope}'] // use driver of myScope
    ]);
    

    // after container initiated
    $container = new Container(new Config(...));
    
    // equals to $cache = $container->get('cache')
    $cache = Container::cache();
    
    // if myservice defined and invokable
    $obj = Container::myservice('test');
    

    use Phoole\Cache\Cache;
    use Psr\Log\LoggerAwareTrait;
    use Psr\Log\LoggerAwareInterface;
    
    class MyClass implements LoggerAwareInterface
    {
         use LoggerAwareTrait;
    
         public function __construct(Cache $cache)
         {
         }
    }
    
    // $cache will be injected automatically
    $obj = Container::create(MyClass::class);
    
    // also 'setLogger' will be executed if defined in 'di.after' section
    $logger = $obj->getLogger();
    

    use Psr\Log\LoggerAwareTrait;
    use Psr\Log\LoggerAwareInterface;
    
    class MyOwnClass implements LoggerAwareInterface
    {
         use LoggerAwareTrait;
         ...
    }
    
    // create your object with arguments
    $obj = Container::create(MyOnwClass::class, [...]);
    
    // $logger injected by the container automatically
    $logger = $obj->getLogger();
    

    $config = [
    
        'di.after' => [
            'setLogger',        // logger aware
            'setCache',         // cache aware
            'setDispatcher',    // event aware
            'setContainer',     // container aware
            ...
        ],
    ];
    ...