简体   繁体   中英

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 . 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?

$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:

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.

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

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:

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.


Are you confusing the cache with "singletons"? Maybe this documentation can help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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