PHP code example of yii1tech / di

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

    

yii1tech / di example snippets




use yii1tech\di\DI;

class Foo
{
    /**
     * @var CDbConnection
     */
    public $db;
    /**
     * @var string 
     */
    public $name = 'default';
    
    public function __construct(CDbConnection $db)
    {
        $this->db = $db;
    }
    
    public function format(CFormatter $formatter, string $value): string
    {
        return $formatter->formatDate($value);
    }
}

$psrContainer = DI::container(); // retrieve related PSR compatible container
var_dump($psrContainer instanceof \Psr\Container\ContainerInterface); // outputs `true`

$db = DI::get(CDbConnection::class); // retrieve entity from PSR compatible container

$object = DI::make(Foo::class); // instantiates object, resolving constructor arguments from PSR compatible container based on type-hints
var_dump($object->db instanceof CDbConnection); // outputs `true`

$date = DI::invoke([$object, 'format'], ['value' => time()]); // invokes given callback, resolving its arguments from PSR compatible container based on type-hints
var_dump($date); // outputs '2023/07/28'

$object = DI::create([ // instantiates object from Yii-style configuration, resolving constructor arguments from PSR compatible container based on type-hints
    'class' => Foo::class,
    'name' => 'custom',
]);
var_dump($object->db instanceof CDbConnection); // outputs `true`
var_dump($object->name); // outputs `custom`


// file '/public/index.php'
;
use yii1tech\di\DI;

// setup DI container:
DI::setContainer(
    Container::new()
        ->config(CDbConnection::class, [
            'connectionString' => 'sqlite::memory:',
        ])
        ->lazy(ICache::class, function (Container $container) {
            $cache = new CDbCache();
            $cache->setDbConnection($container->get(CDbConnection::class))
            
            $cache->init();
            
            return $cache;
        })
        // ...
);

// create and run Yii application:
Yii::createWebApplication($config)->run();


// file '/public/index.php'

use yii1tech\di\DI;

// setup DI container:
DI::setContainer(function () {
    return ContainerFactory::create();
});

// create and run Yii application:
Yii::createWebApplication($config)->run();

// ...
class ContainerFactory
{
    public static function create(): \Psr\Container\ContainerInterface
    {
        $container = Container::new();
        // fill up container
        
        return $container;
    }
}


// file '/public/index.php'
i1tech\di\web\WebApplication;

// setup DI container:
DI::setContainer(/* ... */);

// create and run Yii DI-aware application:
Yii::createApplication(WebApplication::class, $config)->run();


// ...
use yii1tech\di\Container;
use yii1tech\di\DI;
use yii1tech\di\web\WebApplication;

// setup DI container:
DI::setContainer(
    Container::new()
        ->lazy(CDbConnection::class, function () {
            $db = new CDbConnection();
            $db->connectionString = 'mysql:host=127.0.0.1;dbname=example';
            $db->username = 'container_user';
            $db->password = 'secret';
            
            $db->init();
            
            return $db;
        })
        ->lazy(ICache::class, function (Container $container) {
            $cache = new CDbCache();
            $cache->setDbConnection($container->get(CDbConnection::class));
            
            $cache->init();
            
            return $cache;
        })
);

$config = [
    'components' => [
        'db' => [ // component 'db' will be fetched from container using ID 'CDbConnection'
            'class' => CDbConnection::class,
        ],
        'cache' => [ // component 'cache' will be fetched from container using ID 'ICache'
            'class' => ICache::class,
        ],
        'format' => [ // if component has no matching definition in container - it will be resolved in usual way
            'class' => CFormatter::class,
            'dateFormat' => 'Y/m/d',
        ],
    ],
];

// create and run Yii DI-aware application:
Yii::createApplication(WebApplication::class, $config)->run();
//...
$db = Yii::app()->getComponent('db');
var_dump($db->username); // outputs 'container_user'

$cache = Yii::app()->getComponent('cache');
var_dump(get_class($cache)); // outputs 'CDbCache'



use yii1tech\di\web\Controller;

class ItemController extends Controller
{
    /**
     * @var CDbConnection 
     */
    protected $db;
    
    // injects `CDbConnection` from DI container at constructor level
    public function __construct(CDbConnection $db, $id, $module = null)
    {
        parent::__construct($id, $module); // do not forget to invoke parent constructor
        
        $this->db = $db;
    }
    
    // injects `ICache` from DI container at action level
    public function actionIndex(ICache $cache)
    {
        // ...
    }
    
    // injects `ICache` from DI container at action level, populates `$id` from `$_GET`
    public function actionView(ICache $cache, $id)
    {
        // ...
    }
}



use yii1tech\di\console\ConsoleCommand;

class ItemCommand extends ConsoleCommand
{
    /**
     * @var CDbConnection 
     */
    protected $db;
    
    // injects `CDbConnection` from DI container at constructor level
    public function __construct(CDbConnection $db, $name, $runner)
    {
        parent::__construct($name, $runner); // do not forget to invoke parent constructor

        $this->db = $db;
    }
    
    // injects `ICache` from DI container at action level
    public function actionIndex(ICache $cache)
    {
        // ...
    }
    
    // injects `CFormatter` from DI container at action level, populates `$date` from shell arguments
    public function actionFormat(CFormatter $formatter, $date)
    {
        // ...
    }
}


// file '/public/index.php'
se yii1tech\di\DI;
use yii1tech\di\web\WebApplication;

// use 'PHP-DI' for the container:
DI::setContainer(function () {
    $builder = new ContainerBuilder();
    
    $builder->useAutowiring(true);
    // ...
    
    return $builder->build();
});

// create and run Yii DI-aware application:
Yii::createApplication(WebApplication::class, $config)->run();


// file '/public/index.php'
se yii1tech\di\DI;
use yii1tech\di\external\ContainerBasedInjector;
use yii1tech\di\web\WebApplication;

// use 'PHP-DI' for the container:
DI::setContainer(function () {
    $builder = new ContainerBuilder();
    // ...
    
    return $builder->build();
})
    ->setInjector(new ContainerBasedInjector()); // use `\DI\Container::make()` and `\DI\Container::call()` for dependency injection

// create and run Yii DI-aware application:
Yii::createApplication(WebApplication::class, $config)->run();



// file '/public/index.php'
ontainerBuilder;
use yii1tech\di\DI;
use yii1tech\di\external\ContainerProxy;

// use 'PHP-DI' for the container:
DI::setContainer(function () {
    $builder = new ContainerBuilder();
    // ...
    
    return ContainerProxy::new($builder->build())
        ->setCallbackForHas(function (Container $container, string $id) {
            return in_array($id, $container->getKnownEntryNames(), true);
        });
});
// ...

php composer.phar