PHP code example of goez / di

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

    

goez / di example snippets


use Goez\Di\Container;
$container = Container::createInstance();

class App
{
    private $appName;

    public function __construct($appName = 'ThisApp')
    {
        $this->appName = $appName;
    }
    
    public function getAppName()
    {
        return $this->appName;
    }
}

$app = $container->make(App::class);
echo $app->getAppName(); // ThisApp

$app = $container->make(App::class, ['MyApp']);
echo $app->getAppName(); // MyApp

class App
{
    private $auth;
    private $appName;

    public function __construct(Auth $auth, $appName = 'ThisApp')
    {
        $this->auth = $auth;
        $this->appName = $appName;
    }
}

class Auth {}

$app = $container->make(App::class);

class App
{
    private $auth;
    private $appName;

    public function __construct(Auth $auth, $appName = 'ThisApp')
    {
        $this->auth = $auth;
        $this->appName = $appName;
    }
}

class Auth 
{
    private $db;
    
    public function __construct(Db $db)
    {
        $this->db = $db;
    }
}

$app = $container->make(App::class);

$container->bind('db', function ($container) {
    return new Db();
});
$db = $container->make('db');

interface DbInterface {}

class Db implements DbInterface {}

$container->bind(DbInterface::class, Db::class);
$db = $container->make(DbInterface::class);

interface DbInterface {}

class Db implements DbInterface {}

$container->instance(DbInterface::class, new Db());
$db1 = $container->make(DbInterface::class);

$container->instance(DbInterface::class, new Db());
$db2 = $container->make(DbInterface::class);

assert($db1 !== $db2); // true

interface DbInterface {}

class Db implements DbInterface {}

$container->singleton(DbInterface::class, function (Container $c) {
    return $c->make(Db::class);
    // Or
    return new Db();
});
$db1 = $container->make(DbInterface::class);
$db2 = $container->make(DbInterface::class);

assert($db1 === $db2);

interface DbInterface {}

class Db implements DbInterface {}

$container->singleton(DbInterface::class, new Db());
$db1 = $container->make(DbInterface::class);
$db2 = $container->make(DbInterface::class);

assert($db1 === $db2);