1. Go to this page and download the library: Download thamtech/yii2-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/ */
thamtech / yii2-di example snippets
use yii\db\Connection;
// returns Yii::$app->db
$db = \thamtech\di\Instance::ensure('db', [
Connection::class,
\yii\redis\Connection::class,
]);
// returns an instance of Connection using the given configuration.
// * the first type listed is used as the 'class' parameter when it isn't
// specified in the reference array
$db = \thamtech\di\Instance::ensureAny([
'dsn' => 'sqlite:path/to/my.db'
], [
Connection::class,
\yii\redis\Connection::class,
])
class ExpensiveInstanceProvider implements \thamtech\di\Provider
{
public function get()
{
// instantiate $object
// ...
return $objectInstance;
}
}
class DependendClass
{
private $provider;
public function __construct(ExpensiveInstanceProvider $provider)
{
$this->provider = $provider;
}
public function fooBar()
{
$objectInstance = $provider->get();
}
}
namespace example\package;
class FooCacheProvider extends \thamtech\di\InstanceProvider {}
class BarCacheProvider extends \thamtech\di\InstanceProvider {}
class FooCacheUtil
{
private $cache;
// dependency injection provides a FooCacheProvider
public function __construct(FooCacheProvider $cacheProvider)
{
$this->cache = $cacheProvider->get();
}
}
class BarCacheUtil
{
private $cache;
// dependency injection provides a BarCacheProvider
public function __construct(BarCacheProvider $cacheProvider)
{
$this->cache = $cacheProvider->get();
}
}
// application's container configuration
'container' => [
'singletons' => [
'example\package\FooCache:::provided' => [
'class' => 'yii\caching\ArrayCache',
],
'example\package\BarCache:::provided' => [
'class' => 'yii\caching\DbCache',
],
],
],
namespace example\package;
class FooCacheProvider extends \thamtech\di\InstanceProvider
{
public $class = 'yii\caching\ArrayCache';
public $config = [
'serializer' => false,
'defaultDuration' => 3600,
];
}
namespace example\package;
class FooCacheProvider extends \thamtech\di\InstanceProvider
{
public $ensureTypes = [
'yii\caching\ArrayCache',
'yii\caching\FileCache',
];
}
'container' => [
'singletons' => [
'example\package\FooCache:::provided' => [
'class' => 'yii\caching\DbCache',
],
],
],
$fooCacheProvider = new FooCacheProvider();
$fooCacheProvider->get(); // will throw an InvalidConfigException
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.