PHP code example of phossa / phossa-di

1. Go to this page and download the library: Download phossa/phossa-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/ */

    

phossa / phossa-di example snippets


  class MyCache
  {
      private $driver;

      public function __construct(MyCacheDriver $driver)
      {
          $this->driver = $driver;
      }

      // ...
  }

  class MyCacheDriver
  {
      // ...
  }
  

  use Phossa\Di\Container;

  $container = new Container();

  // use the 'MyCache' classname as the service id
  if ($container->has('MyCache')) {
      $cache = $container->get('MyCache');
  }
  

  use Phossa\Di\Container;

  // turn off auto wiring
  $container = (new Container())->auto(false);

  // config service with id, classname and constructor arguments
  $container->add('cache', 'MyCache', [ '@cacheDriver@' ]);

  // add initialization methods
  $container->add('cacheDriver', 'MyCacheDriver')
            ->addMethod('setRoot', [ '%cache.root%' ]);

  // set a parameter which is referenced before
  $container->set('cache.root', '/var/local/tmp');

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

    $container = new Container();

    // add the 'cache' service definition
    $container->add('cache', \Phossa\Cache\CachePool::class, ['@cacheDriver@']);

    // add the 'cacheDriver' service definition
    $container->add('cacheDriver', \Phossa\Cache\Driver\FilesystemDriver);

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

    // will resolve this ['@cache@', 'setLogger'] to a real callable
    $container->run(['@cache@', 'setLogger'], ['@logger@']);
    

    // set system temp directory
    $container->set('system.tmpdir', '/var/tmp');

    // point cache dir to system temp
    $container->set('cache.dir', '%system.tmpdir%');

    // set with array of vales
    $container->set('logger', [
        'driver' => 'Phossa\Logger\Driver\StreamDriver',
        'level'  => 'warning'
    ]);

    // use parameter
    $container->add(
        'cacheDir',
        Phossa\Cache\Driver\Filesystem::class,
        [ '%cache.dir%' ]
    );
    

  // ...
  $container->add('cacheDriver', function() {
      return new \MyCacheDriver();
  });
  

  
  /* file name '*.s*.php' indicating SERVICE definitions in PHP format */
  use Phossa\Di\Container;
  return [
      'cache' => [
          'class' => [ 'MyCache', [ '@cacheDriver@' ]],
          'scope' => Container::SCOPE_SHARED // default anyway
      ],
      'cacheDriver' => [
          'class'   => 'MyCacheDriver',
          'methods' => [
              [ 'setRoot', [ '%cache.root%' ] ],
              // ...
          ]
      ],
      'theDriver'  => '@cacheDriver@', // an alias
      // ...
  ];

  

  
  /* file name '*.p*.php' indicating PARAMETER definitions in PHP format */
  return [
      'tmp.dir' => '/var/local/tmp',
      'cache.root' => '%tmp.dir%',
      // ...
  ];

  

  
  /* file name '*.php' indicating definitions in PHP format */
  use Phossa\Di\Container;
  return [
      // key 'services' indicating the service definitions
      'services' => [
          'cache' => [
              'class' => [ 'MyCache', [ '@cacheDriver@' ]],
              'scope' => Container::SCOPE_SHARED // default anyway
          ],
          'cacheDriver' => [
              'class'   => 'MyCacheDriver',
              'methods' => [
                  [ 'setRoot', [ '%cache.root%' ] ],
                  // ...
              ]
          ],
          // ...
      ],

      // key 'parameters' indicating the parameter definitions
      'parameters' => [
          'cache.root' => '/var/local/tmp',
          // ...
      ],

      // key 'mappings' indicating the mapping definitions
      'mappings' => [
          'Phossa\\Cache\\CachePoolInterface'  => 'Phossa\\Cache\\CachePool',
          // ...
      ],
  ];

  

  use Phossa\Di\Container;

  $container = new Container();

  // load service definitions
  $container->load('./definition.serv.php');

  // load parameter definition
  $container->load('./definition.param.php');

  // you may load from one if you want to
  // $container->load('./definition.php');

  // getting what you've already defined
  $cache = $container->get('cache');
  

  // map an interface to a classname
  $container->map(
      'Phossa\\Cache\\CachePoolInterface', // MUST NO leading backslash
      'Phossa\\Cache\\CachePool' // leading backslash is optional
  );

  // map an interface to a service id, MUST NO leading backslash
  $container->map('Phossa\\Cache\\CachePoolInterface', '@cache@');

  // map an interface to a parameter, no leading backslash
  //$container->map('Phossa\\Cache\\CachePoolInterface', '%cache.class%');
  

  $container->load('./defintion.map.php');
  

  // turn off auto wiring
  $container->auto(false);

  // turn on auto wiring
  $container->auto(true);
  

  use Phossa\Di\Delegator;

  // create delegator
  $delegator = new Delegator();

  // insert different containers
  $delegator->addContainer($otherContainer);

  // $contaner register with the delegator
  $container->setDelegate($delegator);

  // cacheDriver is now looked up through the $delegator
  $cache = $container->get('cache');
  

  // any object implementing 'LoggerAwareInterface' should be decorated
  $container->addDecorate(
      'setlogger',  // rule name
      'Psr\\Log\\LoggerAwareInterface', // NO leading backslash
      ['setLogger', ['@logger@']] // run this method
  );
  

  $container->addDecorate('setlogger',
      function($object) {
          return $object instanceof \Psr\Log\LoggerAwareInterface;
      },
      function($object) use($container) {
          $object->setLogger($container->get('logger'));
      }
  );
  

  // SYSTEM_CONST can be 'PRODUCTION' or 'DEVELOPMENT'
  $container->setTag(SYSTEM_CONST);

  // load different defintion base on container tags
  if ($container->hasTag('PRODUCTION')) {
      $container->load('./productDefinitions.php');
  } else {
      $container->load('./developDefinitions.php');
  }
  

  

  use Phossa\Di\Extension\Provider\ProviderAbstract;

  // Production related DB definitions here
  class ProductionDbProvider extends ProviderAbstract
  {
      // list of service ids we provide
      protected $provides = [ 'DbServer' ];

      // tags this provide has
      protected $tags = [ 'PRODUCTION' ];

      // the only method we need to implement
      protected function merge()
      {
          $container = $this->getContainer();
          $container->add('DbServer', '\\DbClass', [
              '192.168.0.12', 'myDbusername', 'thisIsApassword'
          ]);
      }
  }

  

  // SYSTEM_CONST is now 'PRODUCTION'
  $container->setTag(SYSTEM_CONST);

  // the provider will be loaded only if SYSTEM_CONST is PRODUCTION
  $container->addProvider(new ProductionDbProvider());

  // another provider will be loaded only if SYSTEM_CONST is TEST
  $container->addProvider(new TestDbProvider());

  // DB related definitions will be loaded here
  $db = $container->get('DbServer');
  

  $container = new Container('./defintions.php', [
      ProductionDbProvider::class,
      TestDbProvider::class
  ]);
  

  // a shared copy of cache service
  $cache1 = $container->get('cache');

  // a new cache instance
  $cache2 = $container->one('cache');

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

  // but both share the same cacheDriver
  var_dump($cache1->getDriver() === $cache2->getDriver()); // true
  

  $container->add('cache', '\\Phossa\\Cache\\CachePool')
            ->setScope(Container::SCOPE_SINGLE);

  // each get() will return a new cache
  $cache1 = $container->get('cache');
  $cache2 = $container->get('cache');

  // different instances
  var_dump($cache1 === $cache2); // false

  // dependencies are shared
  var_dump($cache1->getDriver() === $cache->getDriver()); // true
  

  // make everything non-shareable, set default scope to SCOPE_SINGLE
  $container->share(false);

  // this will return a new copy of cache service
  $cache1 = $container->get('cache');

  // this will return a new copy also
  $cache2 = $container->get('cache');

  // FALSE
  var_dump($cache1 === $cache2);

  // dependencies are different
  var_dump($cache1->getDriver() === $cache->getDriver()); // false
  

    if ($container->hasTag('PRODUCTION')) {
        $container->load('./productDefinitions.php');
    } else {
        $container->load('./developDefinitions.php');
    }
    

    use Phossa\Di\Delegator;

    // create the delegator
    $delegator = new Delegator();

    // other container register with the delegator
    $delegator->addContainer($otherContainer);

    /*
     * register $container with its auotwiring status unchanged (last container)
     * but $otherContainer's autowiring will be forced off
     */
    $container->setDelegate($delegator);

    // dependency will be resolved in the order of $otherContainer, $container
    // ...