PHP code example of edvin / hbcontainer

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

    

edvin / hbcontainer example snippets




// Helper functions for definitions:
use function \HbLib\Container\resolve;
use function \HbLib\Container\reference;
use function \HbLib\Container\factory;

interface MyInterface {}
class MyClass implements MyInterface {}
    
class MyClass2 {
    public $value;
    
    function __construct($value) {
        $this->value = $value;
    }
}
    
class MyClass3 {
    public $value;
    
    function __construct(MyInterface $value) {
        $this->value = $value;
    }
}

class MyClass4 implements MyInterface {}
class MyManager {
    function __construct(string $type) {}
    
}

$definitions = array(
    // Factories:
    'session' => factory(function() { return true; }),
    'lol' => factory(function() { return false; }),
    'hello' => factory(function() { return null; }),
    MyManager::class => factory(function() { return new MyManager('someType'); }),
    
    MyInterface::class => resolve(MyClass::class),
    
    // Providing the class to resolve is not > null

// PSR-11
$container->has('session'); // => true
$container->has('where'); // => false
$container->has('hello'); // => true



//...
$builder = new \HbLib\Container\ContainerBuilder(new \HbLib\Container\DefinitionSource([
    //...
]));

$filePath = sys_get_temp_dir() . '/CompiledContainer.php';
$builder->enableCompiling($filePath); // important step

if (!is_file($filePath)) {
    $builder->writeCompiled();
}

$container = $builder->build();


// compile_container.php

// load build just like you would in web app:
$builder = new \HbLib\Container\ContainerBuilder(new \HbLib\Container\DefinitionSource([
    //...
]));

$filePath = sys_get_temp_dir() . '/CompiledContainer.php';
$builder->enableCompiling($filePath); // important step
$builder->writeCompiled();