PHP code example of kode / di

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

    

kode / di example snippets


use Kode\DI\Container;

$container = new Container();

// 绑定单例
$container->singleton(LoggerInterface::class, FileLogger::class);

// 绑定原型
$container->prototype(Request::class);

// 获取实例
$logger = $container->get(LoggerInterface::class);

use Kode\DI\Attributes\Inject;
use Kode\DI\Attributes\Singleton;

#[Singleton]
class UserService
{
    #[Inject]
    private LoggerInterface $logger;

    #[Inject(id: 'cache.ttl', 

use Kode\DI\ContextualContainer;

// 在协程环境中自动隔离实例
ContextualContainer::setContainer($container);

// 每个协程拥有独立实例
ContextualContainer::resolve(DatabaseConnection::class);

use Kode\DI\ServiceProvider;

class DatabaseServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->singleton(DatabaseInterface::class, MySQLDatabase::class);
    }

    public function boot(): void
    {
        // 启动逻辑
    }
}

// 当 UserController 需要 LoggerInterface 时,使用专门的实现
$container->when(UserController::class)
    ->needs(LoggerInterface::class)
    ->give(UserLogger::class);

// 使用闭包
$container->when(OrderController::class)
    ->needs(LoggerInterface::class)
    ->give(fn($c) => new OrderLogger('order.log'));

// 给服务打标签
$container->singleton(CacheInterface::class, RedisCache::class)->tag('cache');
$container->singleton(SessionInterface::class, RedisSession::class)->tag('cache');

// 获取所有带标签的服务
$cacheServices = $container->tagged('cache');

use Kode\DI\Container;
use Kode\Attributes\Attr;
use Kode\Context\Context;

// 自动使用 kode/attributes 进行属性读取
// 可选使用 kode/context 进行协程上下文隔离