PHP code example of njeaner / di-container

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

    

njeaner / di-container example snippets


composer 

$container = new \NJContainer\Container\Container();

$containerDefinition = new \NJContainer\Container\ContainerDefinition();

$instance = new \NJContainer\Container\InstanceDefinition();
// or
$instance = new \NJContainer\Container\InstanceDefinition($containerDefinition);


$container = new \NJContainer\Container\Container($instance);

/**
 * @param id string
 * @param mixed $definition
 * @param bool $shared, if "true" container will save this definition instance as a factory dependency
*/
$container->set($id, $definition)
$container->set($id, $definition, true)

/**
 * @param <string, array> $definitions
 * @example [
 *      'name'=> ['John Doe'],
 *      'stdClass1'  => [new stdClass()],
 *      \Namespace\Route::class => [new \Namespace\Route(), true]
 * ];
 * The true value as second item in dependency array means that you are storing an= factory dependency
*/
$container->add($definitions)

/**
 * @param string $definitionsPath, path directory of definition file
*/
$container->addDefinition($definitionsPath)

/**
 * @param string $id definition id
 * @param string $name parameter name
 * @param mixed $parameter param value to set in definition
*/
$container->setParameter($id, $name, $parameter)

/**
 * @param string $id definition id
 * @param array $parameters
*/
$container->setParameters($id, $parameters)

/**
 * @param string $id
 * @param bool $shared, if "true" container with retrieve a factory dependency
*/
$container->get($id)
$container->get($id, true)

class Foo{

}

class Bar {
    public function __construct(Foo $foo, $type = 'Bar'){
        $this->foo = $foo;
        $this->type = $type
    }
}

class FooBar{
    public function __construct(Foo $foo , string $name, array $params){

    }
}

    # config.php
    # dependency configuration file


    
    return [
        'name'=> 'John Doe',
        FooBar::class => get()->setParameters(
            'name' => get('name'),
            'params' => ['type' => FooBar::class]
        )
    ];
    

$container = new \NJContainer\Container\Container();

$container->addDefinition('config.php');
$arrayDefinition = [
    FooBar::class => get()->setParameters(
        'params' => add(['bool' => false])
    )
 ];
 
$container->add($arrayDefintion);
$container->lock();

$fooObject = $container->get(Foo::class);
$barObject = $container->get(Foo::class);
// Foo::class and Bar::class has been resolved using autowiring

$foobar = $container->get(FooBar::class);