PHP-DI 5 值与定义缓存相关技术咨询
PHP-DI 5 Cache Behavior Questions Answered
Hey there! Let's break down your two questions about PHP-DI 5's caching and entry handling clearly:
1. Will an object set directly in the container be cached?
First, let's clarify two distinct "caching" layers in PHP-DI 5 to avoid confusion:
- Persistent definition cache (the file-based cache you likely researched): When you set an object directly like
$container->set('MyService', new MyService());, this already-instantiated object won't be stored in the persistent definition cache. That cache only serializes and stores definition configurations (like factory closures, array definitions, or class references) to speed up container initialization on subsequent requests—it doesn't cache live object instances. - In-memory singleton cache: By default, PHP-DI treats all entries as singletons. So once you set that object instance, it will stay in the container's memory for the rest of the request lifecycle. This is temporary in-memory storage, not the persistent definition cache you configure via settings like
DefinitionCache.
2. What happens if an entry is already defined in the container's definition files?
This depends on the specific operation you're performing, so let's cover the common scenarios:
- Duplicate definitions in definition files: If you define the same entry multiple times (e.g., two entries for
MyServiceacross your definition files), PHP-DI 5 will silently use the last definition it encounters during initialization. No errors are thrown—it just overwrites the previous definition without fanfare. - Overwriting a defined entry at runtime: If you load your definition files first, then later call
$container->set('MyService', $newValue)in your code:- If the entry hasn't been instantiated yet, the runtime definition will overwrite the one from your files. This happens silently in memory and won't modify your persistent definition cache file.
- If the entry was already instantiated and cached in memory, the runtime
set()will replace that in-memory instance with your new value. Again, no errors are triggered—this is handled silently unless you've enabled strict mode (which isn't the default in PHP-DI 5).
内容的提问来源于stack exchange,提问作者user7941334
相关产品推荐
相关产品推荐

