PHP code example of luoluolzb / di
1. Go to this page and download the library: Download luoluolzb/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/ */
luoluolzb / di example snippets
use luoluolzb\di\Container;
$container = new Container();
// 注入匿名函数
$container->set('logger', function($c) {
$logger = new Monolog\Logger;
$logger->pushHandler(new Monolog\Handler\StreamHandler('app.log', Logger::WARNING));
return $logger;
});
// 注入类实例
$container->set('myClass', new MyClass());
// 注入数组
$container->set('configs', ([
'db' => [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'test',
'port' => '3306',
'user' => 'root',
'password' => '123456',
],
]);
// 注入标量
$container->set('isExists', true);
$container->set('pdo', function($c) {
// $c 为容器实例
$c = $c->get('configs')['db'];
$dsn = "{$c['type']}:host={$c['host']};port={$c['port']};dbname={$c['dbname']};";
return new PDO($dsn, $c['user'], $c['password']);
});
$container = new Container([
'logger' => function($c) {
$logger = new Monolog\Logger;
$logger->pushHandler(new Monolog\Handler\StreamHandler('app.log', Logger::WARNING));
return $logger;
},
'myClass' => new MyClass(),
'configs' => [
'db' => [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'test',
'port' => '3306',
'user' => 'root',
'password' => '123456',
],
],
]);
// 注入匿名函数
$container->factory('myClass', function($c) {
return MyClass();
});
$container = new Container([
'logger' => function($c) {
$logger = new Monolog\Logger;
$logger->pushHandler(new Monolog\Handler\StreamHandler('app.log', Logger::WARNING));
return $logger;
},
'myClass' => function($c) {
return MyClass();
},
], [
'logger' => true,
]);
$logger = $container->get('logger');
$logger->info('some info');
$container->set('db', function($c) {
return Db::getInstance();
});
$container->delete('logger');
if ($container->has('logger')) {
// ...
} else {
// ...
}
// 注入实体
$container['configs'] = [
'db' => [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'test',
'port' => '3306',
'user' => 'root',
'password' => '123456',
],
];
// 获取实体
$dbConf = $container['configs']['db'];
// 删除实体
unset($container['configs']);
// 判断实体是否存在
$ret = isset($container['configs']);
$count = $container->count();
$count = count($container);