PHP code example of modethirteen / opencontainer

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

    

modethirteen / opencontainer example snippets


$container = new OpenContainer();

class Baz {

  private Foo $foo;
  private Bar $bar;

  public function __construct(IContainer $container) {
    $this->foo = $container->Foo;
    $this->bar = $container->Bar;
  }
  
  public function doSomething() : string {
    return $this->foo->myMethod();
  }
}

/**
 * setup the type as a virtual property so that IDE's that support type checking can take advantage
 *
 * @property Foo $Foo
 */
class MyContainer extends OpenContainer {
}

$container = new MyContainer();
$container->registerType('Foo', Foo::class);

// type checks will infer this object to be an instance of Foo
$instance = $container->Foo;

/**
 * setup the type as a virtual property so that IDE's that support type checking can take advantage
 *
 * @property Bar $Bar
 */
class MyContainer extends OpenContainer {
}

$container = new MyContainer();
$container->registerInstance('Bar', new Bar($dependency, $outside, $of, $container));

// type checks will infer this object to be an instance of Bar
$instance = $container->Bar;

/**
 * setup the type as a virtual property so that IDE's that support type checking can take advantage
 *
 * @property Qux $Qux
 */
class MyContainer extends OpenContainer {
}

$container = new MyContainer();
$container->registerBuilder('Qux', function(MyContainer $container) : Qux {

  // builder functions only have one argument, access to the container itself
  return new Qux($container, $some, $other, $dependency);
});

// type checks will infer this object to be an instance of Qux
$instance = $container->Qux;

$container = (new OpenContainer)->toDeferredContainer();

// all methods on a deferred container are identical to a non-deferred container
$container->registerType('Plugh', Plugh::class);
$container->registerInstance('Plugh', new Plugh());

// closure function style builders