PHP code example of phossa2 / di

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

    

phossa2 / di example snippets


  // file cache.php
  class MyCache
  {
      private $driver;

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

      // ...
  }

  class MyCacheDriver
  {
      // ...
  }
  

  use Phossa2\Di\Container;

  // should be aware of these classes
  yCache' classname as the service id
  if ($container->has('MyCache')) {
      $cache = $container->get('MyCache');
  }
  

  use Phossa2\Di\Container;

  // should be aware of these classes
  n off autowiring
  $container->auto(false);

  // define service with an array
  $container->set('cache', [
      'class' => 'MyCache', // classname
      'args'  => ['${#driver}'] // constructor arguments
  ]);

  // add service 'driver' with a callback
  $container->set('driver', function() {
      return new \MyCacheDriver();
  });

  // get the service
  var_dump($container->get('cache') instanceof \MyCache); // true
  

  use Phossa2\Di\Container;
  use Phossa2\Config\Config;

  $configData = [
      // container service definitions
      'di.service' => [
          // cache service
          'cache'  => ['class' => 'MyCache', 'args' => ['${#driver}']],

          // cache driver, classname directly
          'driver' => 'MyCacheDriver',
      ],

      // common methods to run after each instantiation
      'di.common' => [
          [
            function($obj) { return $obj instanceof \MyCacheDriver; }, // tester
            function($obj, $container) { echo "ok"; } // runner
          ],
      ],

      // init methods after container created
      'di.init' => [
            // default section
            'default' => [
                ['setLogger', ['${#logger}']],
                // ...
            ],

            // my own section
            'mystuff' => [
            ],
      ],
  ];

  // create $config instance with provided data
  $config = new Config(null, null, $configData);

  // instantiate container with $config instance and definition base node 'di'
  $container = new Container($config, 'di');

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

  // true
  var_dump($cache instanceof \MyCache);
  

    // define a new parameter for the container
    $container->param('cache.dir', '${system.tmpdir}/cache');

    // use the cache.dir parameter defined above
    $container->set('cache', [
        'class' => '${cache.class}', // predefined in file
        'args'  => ['${cache.dir}']  // just defined above
    ]);
    

    $container->set('cache', [
        'class' => '${cache.class}',
        'args'  => ['${#cache_driver}'] // service reference
    ]);
    

    // run(callable, arguments) with references
    $container->run(['${#logger}', 'warning'], ['warning from ${log.facility}']);

    // resolve references
    $data = ['${system.dir}', '${#logger}'];
    $container->resolve($data); // all references in $data are now resolved
    

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

  // map an interface to a service id reference
  $container->set('Phossa2\\Cache\\CachePoolInterface', '${#cache}');

  // map an interface to a parameter reference
  $container->set('Phossa2\\Cache\\CachePoolInterface', '${cache.class}');

  // map an interface to a callback
  $container->set('Phossa2\\Cache\\CachePoolInterface', function() {
      return new \Phossa2\Cache\CachePool();
  });
  

  $configData = [
      // ...
      'di.service' => [
          'Phossa2\\Cache\\CachePoolInterface' => '${cache.class}',
          // ...
      ],
      // ...
  ];
  

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

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

    $container->set('cache', [
        'class'   => 'Phossa2\\Cache\\Cache',
        'args'    => ['${#cachedriver}'], // constructor arguments
        'methods' => [
            ['clearCache'], // method of $cache
            ['setLogger', ['${#logger}']], // method with arguments
            [[$logger, 'setLabel'], ['cache_label']], // callable with arguments
            [['${#driver}, 'init']], // pseduo callable
            // ...
        ],
    ]);
    

    $configData = [
        // common methods for all instances
        'di.common' => [
            // [ tester(): bool, method ]
            [
                function($object, $container) {
                    return $object instanceof 'Psr\\Log\\LoggerAwareInterface'
                },
                ['setLogger', ['${#logger}']]
            ],
            // ...
        ],
    ];
    

    $container->set('logger', [
        'class' => 'Phossa2\Logger\Logger',
        'skip'  => true
    ]);
    

  use Phossa2\Di\Delegator;

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

  // create container
  $container = new Container();

  // insert container into delegator
  $delegator->addContainer($container);

  // get from delegator now
  $cache = $delegator->get('cache');
  

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

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

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

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

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

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

    $container->set('cache', [
        'class' => '\\Phossa2\\Cache\\CachePool'),
        'scope' => Container::SCOPE_SINGLE
    ]);

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

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

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

    // set default scope to SCOPE_SINGLE
    $container->share(false);

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

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

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

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

    // instance in scope 'myScope'
    $cacheOfMyScope = $container->get('cache@myScope');

    // new instance in single scope, even though you specified one
    $cacheOfSingle = $container->one('cache@myScope');

    // instance in shared scope
    $cache = $container->get('cache');
    

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

    class A {
        private $b, $c;

        public function __construct(B $b, C $c) {
            $this->b = $b;
            $this->c = $c;
        }

        public function getB() {
            return $this->b;
        }

        public function getC() {
            return $this->c;
        }
    }

    class B {
        private $c;
        public function __construct(C $c) {
            $this->c = $c;
        }
    }

    class C {
    }

    // an instance of A
    $a1 = $container->one('A');

    // another instance of A
    $a2 = $container->one('A');

    // $a1 and $a2 is different
    var_dump($a1 !== $a2); // true

    // C is the same under A
    var_dump($a1->getC() === $a1->getB()->getC()); // true

    // C is also shared among different A
    var_dump($a1->getC() === $a2->getC()); // true
    

    // this scope only takes effect when under service A
    $container->set('C', [ 'class' => 'C', 'scope' => '#A']);

    // an instance of A
    $a1 = $container->one('A');

    // another instance of A
    $a2 = $container->one('A');

    // C is different among different A
    var_dump($a1->getC() !== $a2->getC()); // true

    // C is same under one A
    var_dump($a1->getC() === $a1->getB()->getC()); // true
    

  $container = new Container();
  $delegator = new Delegator();

  $delegator->addContainer($container);

  // equals to $delegator->has('A')
  if (isset($delegator['A'])) {
      var_dump($delegator['A'] === $container['A']); // true
  }
  

  $container = new Container();
  $container->setWritable(false);

  var_dump($container->isWritable() === false); // true

  // delegator also
  $delegator = new Delegator();
  $delegator->setWritable(false);

  var_dump($delegator->isWritable() === false); // true
  

    $value = [
        'class' => mixed,   // classname/object/callback etc.
        'args'  => array,   // arguments for the constructor or callback
        'scope' => string,  // default scope for this service
        'skip'  => bool,    // skip common methods for the instance
    ];