I am trying to do a service that is instantiated only one time. And then re-used any time I need it when a new user access my homepage.
What I am trying to do is a service once instantiated that set a datetime. When any user connect to my homepage, I send a datetime to my service and I compare the two datetimes (the one when the service had been instantiated and the one of the user), if hour >= 1 then do something.
My problem is that when I refresh my homepage the datetime of the service is the time of right now and not the time when I instantiated it for the first time. It seems that when I refresh it recreates a new service and that's not what I want it to do. I checked in prod and dev, it does not change anything. Is there any way I could do that or are the services not meant to work that way? If so, how could I do that?
Thank you guys for your help!
You can't achieve it in php
directly. For php
every call (page refresh) is a separate request, so every call creates a new instance of your class (defined as a service) - this new instance knows nothing about previous one with datetime set.
You can solve this problem in (at least) two ways:
1. Session
Create your service class and store current datetime in session. Next time your service is called (and instantiated) you will check previous request time. Downside of this solution is that session will time out and is specific to user and as far as I understood well you want to have this no matter which user calls your action. See solution number 2
2. Persistence
Save your datetime in some persistent layer - for example database or file. Then you can read in your service from this data source and tell what is time difference between current and previous request (and you don't worry about user or session timeout)