简体   繁体   English

PHP-DI 5:值和定义的缓存

[英]PHP-DI 5: Caching of values and definitions

I am using the PHP-DI 5 dependency injection container and I have already read the documentation about the definitions caching . 我正在使用PHP-DI 5依赖项注入容器,并且已经阅读了有关定义缓存的文档。 Though I am still not sure in this regard... So I would like to ask you: 尽管我仍然不确定这方面...所以我想问你:

1) If I directly set an object as an entry value in the container, will the entry be cached? 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) Now let's say the object is already defined in the container, in a definitions file: 2)现在假设对象已经在容器的定义文件中定义:

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

If I perform the following: 如果我执行以下操作:

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

// Will this entry be cached?
$container->set(ResponseInterface::class, DI\get('response'));
  • will the entry be cached, or 条目将被缓存,或
  • will an error be raised, or 会引发错误,还是
  • will the entry be "silently" not cached? 条目将被“静默地”缓存吗?

Thank you very much. 非常感谢你。

It seems you are confused as to what "caching" means. 似乎您对“缓存”的含义感到困惑。

What is cached are definitions . 缓存的是定义 A definition describes how to create an object. 定义描述了如何创建对象。 It is cached because reading the configuration files, or reading PHP's reflection, or reading annotations can be expensive. 缓存它是因为读取配置文件,读取PHP的反射或读取注释可能很昂贵。

1) If I directly set an object as an entry value in the container, will the entry be cached? 1)如果我直接将对象设置为容器中的条目值,该条目是否会被缓存?

Since the object is set directly there is no definition. 由于直接设置对象,因此没有定义。 So there is nothing cached. 因此,没有任何缓存。

2) Now let's say the object is already defined in the container, in a definitions file: 2)现在假设对象已经在容器的定义文件中定义:

If the definition is a closure (anonymous function) like in your example then it will not be cached because closures cannot be stored into a cache. 如果像您的示例中那样定义是一个闭包(匿名函数),则它将不会被缓存,因为闭包无法存储到缓存中。

If you use something else than a closure then the definition will be cached to avoid reading the configuration file at runtime on every HTTP request. 如果您使用的不是闭包,则定义将被缓存以避免在运行时针对每个HTTP请求读取配置文件。


Are you confusing the cache with "singletons"? 您是否将缓存与“单个”混淆? Maybe this documentation can help. 也许此文档可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM