PHP code example of tsufeki / hmcontainer

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

    

tsufeki / hmcontainer example snippets


use Tsufeki\HmContainer\Container;

$c = new Container();

$c->setValue("key", 42);

$c->has("key"); // true
$c->get("key"); // 42
$c->get("non-existent-key"); // throws NotFoundException
$c->getOrDefault("non-existent-key", 5); // 5

use Tsufeki\HmContainer\Definition\Value;

$c->setValue("key", 42);
$c->set("key", new Value(42));

$c->setValue("primes", 2, true);
$c->setValue("primes", 3, true);
$c->setValue("primes", 5, true);
$c->isMulti("primes"); // true
$c->get("primes"); // [2, 3, 5]

$c->setClass("aobject", AClass::class, false, ["dep1", "dep2"]);
$c->get("aobject"); // returns new AClass($c->get("dep1"), $c->get("dep2"))
$c->get("aobject"); // returns the same instance as above

class BClass { }

class CClass {
  public function __construct(BClass $b) { }
}

$c->setClass(BClass::class);
$c->setClass(CClass::class);
$c->get(CClass::class); // correctly contructed CClass object

class DClass {
  /**
   * @param CClass $c
   * @param $d @Inject("dkey")
   */
  public function __construct(BClass $b, $c, $d) { }
}

class Aggregator {
  /**
   * @param SomeInterface[] $impls
   */
  public function __construct(array $impls) { }
}

$c->setClass(SomeInterface::class, ConcreteImplementation1::class, true);
$c->setClass(SomeInterface::class, ConcreteImplementation2::class, true);
$c->setClass(Aggregator::class);
$c->get(Aggregator::class);

class Maybe {
  /**
   * @param $dep @Optional
   */
  public function __construct(Dep $dep = null) { }
}

$c->setClass(DClass::class, null, false, [null, "dep2"]);

use Tsufeki\HmContainer\Definition\Reference;

$c->setClass(DClass::class, null, false, [null, new Reference("dep2")]);

$c->setAlias("alias", "target");
$c->get("alias"); // same as $c->get("target")

$c->setLazy('lazy', new Value(42));
$c->get('lazy'); // a callable $f such that $f() === 42

$myFactory = new MyFactory();
$c->set("mykey", $myFactory);