PHP code example of stratadox / di

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

    

stratadox / di example snippets


// Create container
$container = new DependencyContainer();

// Set service
$container->set('some_service', function () {
    return new SomeService();
});

// Get service
$service = $container->get('some_service');

// Check if service exists
$hasService = $container->has('some_service');

// Remove service
$container->forget('some_service');

// Create container
$container = new ArrayAdapter(new DependencyContainer());

// Set service
$container['some_service'] = function () {
    return new SomeService();
};

// Get service
$service = $container['some_service'];

// Check if service exists
$hasService = isset($container['some_service']);

// Remove service
unset($container['some_service']);

// Create container
$container = AutoWiring::the(new DependencyContainer);

$foo = $container->get(Foo::class);

$container = new DependencyContainer();

$container->set('collaborator', function () {
    return new Collaborator();
});

$container->set('main_service', function () use ($container) {
    return new MainService($container->get('collaborator'));
});

$service = $container->get('main_service');

$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'admin';
$password = 'secret';

$container = new DependencyContainer();
$container->set('database', function () use ($dsn, $username, $password) {
    return new DatabaseConnection($dsn, $username, $password);
});

// Set service
$container->set('some_service', function () {
    return new SomeService();
}, false);