PHP code example of azexsoft / di

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

    

azexsoft / di example snippets


// Bindings
$bindings = [
    FooInterface::class => Foo::class, // Classname binding
    Baz::class => new Baz(), // Object binding
    
    // Closure binding with DI resolving in Closure params
    Bar::class => fn(\Azexsoft\Di\Injector $injector) => $injector->build( 
        Bar::class,
        [
            'config' => $params['barConfig'],
            'someParameter' => 123
        ]
    ),
];

// Service providers
$providers = [
    ApplicationServiceProvider::class,
    new FooServiceProvider(),
];

$container = new \Azexsoft\Di\Container($bindings, $providers);

$foo = $container->get(FooInterface::class); // will be returned Foo
$container->bind(FooInterface::class, OtherFoo::class);
$otherFoo = $container->get(FooInterface::class); // will be returned OtherFoo

$container->bind(Abstract::class, [
    '__class' => Concrete::class, // Concrete classname
    '__construct()' => [
        'simpleParam' => 123,
        'otherSimpleParam' => $params['concreteSomeParam'],
        'someObject' => new Definition(fn(Dependency $d) => $d->getSomeObject()),
    ],
    'someMethod()' => [
        'methodParam' => $params['someMethodParam'],
    ],
    'someProperty' => 321
]);

$container->bind(Abstract::class, function(Injector $injector, Dependency $d) use ($params) {
    $concrete = $injector->build(Concrete::class,  [
        'simpleParam' => 123,
        'otherSimpleParam' => $params['concreteSomeParam'],
        'someObject' => $d->getSomeObject(),
    ]);
    $concrete->someMethod($params['someMethodParam']);
    $concrete->someProperty = 321;
    return $concrete;
});