PHP code example of stratadox / di5

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


// Create container
$di = new Container();

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

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

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

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

// Create container
$di = new ArrayAdapter(new Container());

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

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

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

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

$di = new Container();

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

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

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

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

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

$foo = $di->get('foo', Foo::class);

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