PHP code example of utopia-php / di

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

    

utopia-php / di example snippets




use Utopia\DI\Container;

$di = new Container();

$di->set('age', fn (): int => 25);

$di->set(
    'john',
    fn (int $age): string => 'John Doe is '.$age.' years old.',
    ['age']
);

$john = $di->get('john');

$di->set('config', fn (): array => [
    'dsn' => 'mysql:host=localhost;dbname=app',
    'username' => 'root',
    'password' => 'secret',
]);

$di->set(
    'db',
    fn (array $config): PDO => new PDO(
        $config['dsn'],
        $config['username'],
        $config['password']
    ),
    ['config']
);

$counter = 0;

$di->set('requestId', function () use (&$counter): string {
    $counter++;

    return 'request-'.$counter;
});

$di->get('requestId'); // "request-1"

$child = new Container($di);

$child->get('requestId'); // "request-1" (falls back to the parent cache)

$child->set('requestId', function () use (&$counter): string {
    $counter++;

    return 'request-'.$counter;
});

$child->get('requestId'); // "request-2" (child now uses its own local definition)
$di->get('requestId'); // "request-1" (parent is unchanged)
bash
composer