Files
zhamao-framework/src/ZM/Container/ContainerHolder.php

59 lines
1.6 KiB
PHP
Raw Normal View History

2022-12-25 17:42:32 +08:00
<?php
declare(strict_types=1);
namespace ZM\Container;
use DI;
use DI\Container;
use DI\ContainerBuilder;
2022-12-30 11:30:29 +08:00
use OneBot\Driver\Coroutine\Adaptive;
2022-12-25 17:42:32 +08:00
class ContainerHolder
{
2022-12-30 11:30:29 +08:00
/** @var Container[] */
private static array $container = [];
2022-12-25 17:42:32 +08:00
public static function getEventContainer(): Container
{
2022-12-30 11:30:29 +08:00
$cid = Adaptive::getCoroutine()?->getCid() ?? -1;
if (!isset(self::$container[$cid])) {
self::$container[$cid] = self::buildContainer();
2022-12-25 17:42:32 +08:00
}
2022-12-30 11:30:29 +08:00
return self::$container[$cid];
2022-12-25 17:42:32 +08:00
}
public static function clearEventContainer(): void
{
2022-12-30 11:30:29 +08:00
$cid = Adaptive::getCoroutine()?->getCid() ?? -1;
unset(self::$container[$cid]);
2022-12-25 17:42:32 +08:00
}
private static function buildContainer(): Container
{
$builder = new ContainerBuilder();
2022-12-25 18:15:07 +08:00
$builder->addDefinitions(
new AliasDefinitionSource(),
2022-12-25 17:42:32 +08:00
new DI\Definition\Source\DefinitionArray(config('container.definitions', [])),
2022-12-25 18:15:07 +08:00
);
$builder->useAutowiring(true);
$builder->useAttributes(true);
2023-02-07 16:31:32 +08:00
// 容器缓存
$enable_cache = config('container.cache.enable', false);
if (is_callable($enable_cache)) {
$enable_cache = $enable_cache();
}
if ($enable_cache) {
// 检查 APCu 扩展是否可用
if (!extension_loaded('apcu')) {
logger()->warning('APCu 扩展未加载,容器缓存将不可用');
} else {
$builder->enableDefinitionCache(config('container.cache.namespace', ''));
}
}
2022-12-25 17:42:32 +08:00
return $builder->build();
}
}