PHP-DI 5:缓存值和定义

PHP-DI 5: Caching of values and definitions

我正在使用 PHP-DI 5 依赖注入容器,并且我已经阅读了有关 definitions caching 的文档。虽然我在这方面还不是很清楚。。。所以想请教各位:

1) 如果我直接在容器中设置一个对象作为入口值,这个入口会被缓存吗?

$builder = new ContainerBuilder();
$builder->setDefinitionCache(new ApcCache());
$container = $builder->build();

$response = new Response();

// Will this entry be cached?
$container->set(ResponseInterface::class, $response);

2) 现在假设对象已经在容器中定义,在定义文件中:

return [
    'response' => function () {
        return new Response();
    },
];

如果我执行以下操作:

$builder = new ContainerBuilder();
$builder->setDefinitionCache(new ApcCache());
$container = $builder->build();

// Will this entry be cached?
$container->set(ResponseInterface::class, DI\get('response'));

非常感谢。

您似乎对 "caching" 的含义感到困惑。

缓存的是定义。定义描述了如何创建对象。它被缓存是因为读取配置文件,或读取 PHP 的反射,或读取注释可能很昂贵。

1) If I directly set an object as an entry value in the container, will the entry be cached?

由于对象是直接设置的,所以没有定义。所以没有缓存。

2) Now let's say the object is already defined in the container, in a definitions file:

如果定义是一个闭包(匿名函数),就像您的示例中那样,那么它将不会被缓存,因为闭包无法存储到缓存中。

如果您使用闭包以外的东西,那么定义将被缓存以避免在运行时在每个 HTTP 请求时读取配置文件。


您是否将缓存与 "singletons" 混淆了?也许 this documentation 可以提供帮助。