Slim: Dependency Container Initializes at every request

Created on 8 Feb 2018  Â·  8Comments  Â·  Source: slimphp/Slim

Slim docs say that container is initialized once and is provided where it's needed. Is this once in the application lifecycle or the request response cycle?
I have to create a custom library object which I add as a service to the container. The object is initialized by a JSON file that is downloaded from a http address. The problem that I am facing is that on every single request the datafile is downloaded and object is initialized again. This makes the app very slow. I obseeve similar behavior with any other controller that I register as a service. How do I solve this? I want some sort of static persistence till the server stops

question

All 8 comments

There is no way to solve your problem with Slim directly. I would say what you are doing is a huge anti-pattern regardless of whatever framework / language you are using.

I guess what you could do is cache that file locally at least then it wouldn't pull in something every time

Do you mean that is it Okay for Slim to initialize just every service in container for every single request? How does slim work with professional apps?
I have been working in Python Flask, which is also a microservice framework, and it does provide static persistence.

Pimple is a dependency injection container. Only services that are used get created.

This has nothing to do with the design of Slim, but with the typical lifecycle of PHP-based applications. Everything is initialized on every request. It is a “share-nothing” architecture, which has its pros and cons. Long initializations are better off with some kind of caching - it’s up to you to choose the more appropriate mechanism, be it a flat file, Redis, Memcached, some RDBMS.

As an example, Doctrine Cache is a component that wraps common cache backends such as Memcached and Redis (and it’s not to hard to implement an adapter for another backend you may need) and provides a simple common interface for them all.

Do you mean that is it Okay for Slim to initialize just every service in container for every single request? How does slim work with professional apps?
I have been working in Python Flask, which is also a microservice framework, and it does provide static persistence.

PHP doesn't work like Python. At the end of every request, we tear everything down and start again for the next request. This means that there's no state between requests. Given the number of PHP applications in the world, you can assume that state between requests is not a requirement for "professional apps". This isn't Slim related; it's how PHP works.

In this case, I would download the JSON and cache it to a local file or a fast key value storage like Redis or memcache. You there's plenty of caching libraries for PHP.

@edudobay and @akrabat Thanks a lot for the explanation

Closing as resolved.

Was this page helpful?
0 / 5 - 0 ratings