add container cache config

This commit is contained in:
sunxyw 2023-02-07 16:31:32 +08:00
parent e563ade103
commit e8b6b81dea
No known key found for this signature in database
GPG Key ID: F391C42B19AFFC98
2 changed files with 27 additions and 0 deletions

View File

@ -7,6 +7,7 @@ use OneBot\Driver\Process\ProcessManager;
use Psr\Log\LoggerInterface;
use ZM\Config\Environment;
use ZM\Config\EnvironmentInterface;
use ZM\Config\ZMConfig;
use ZM\Framework;
/*
@ -28,4 +29,15 @@ return [
LoggerInterface::class => fn () => logger(),
EnvironmentInterface::class => Environment::class,
],
// 容器的缓存配置,默认情况下,只有在生产环境下才会启用缓存
// 启用缓存后可以减少重复反射的开销,在首次解析后直接从缓存中读取
// 此功能要求 APCu 扩展,如果你没有安装,将会输出警告并禁用缓存
// 请在更新容器配置后手动执行 `apcu_clear_cache()` 来清除缓存
// 详细介绍请参阅https://php-di.org/doc/performances.html#caching
'cache' => [
// 是否启用缓存,支持 bool、callable
'enable' => fn () => ZMConfig::getInstance()->getEnvironment() === 'production',
'namespace' => 'zm',
],
];

View File

@ -38,6 +38,21 @@ class ContainerHolder
);
$builder->useAutowiring(true);
$builder->useAttributes(true);
// 容器缓存
$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', ''));
}
}
return $builder->build();
}
}