Symfony实例化服务一次,并与几个用户一起使用 [英] Symfony instantiate a service one time and use it with several users

查看:105
本文介绍了Symfony实例化服务一次,并与几个用户一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力做一次只被实例化一次的服务。然后,当新用户访问我的主页时,我需要时再次使用它。
我想要做的是一旦实例化了一个设置datetime的服务。当任何用户连接到我的主页时,我将datetime发送到我的服务,并且比较两个数据时间(服务已被实例化的时间和用户的数据时间),如果hour> = 1则执行某些操作。

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.

我的问题是,当我刷新我的主页时,服务的日期时间是现在的时间,而不是我第一次实例化的时间。看来,当我刷新它重新创建一个新的服务,这不是我想要它做的。我检查了prod和dev,它并没有改变任何东西。有什么办法可以做到这一点,还是这些服务不是这样做的?如果是这样,我该怎么做?

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?

谢谢你们的帮助!

推荐答案

直接在 php 中无法实现。对于 php 每个调用(页面刷新)都是一个单独的请求,所以每个调用都会创建一个新的类的实例(定义为一个服务) - 这个新实例什么也不知道前一个一个日期时间设置。

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。会话

创建您的服务类并将会话中的当前日期时间存储起来。下次您的服务被呼叫(并被实例化)时,您将检查以前的请求时间。该解决方案的缺点是该会话将超时并且对用户是特定的,据我所知,无论哪个用户调用您的操作,都希望这样做。见解决方案号码2

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。持久化

将您的datetime保存在一些持久层中,例如数据库或文件。然后,您可以从此数据源读取您的服务,并告知当前和上一个请求之间的时差是什么(您不用担心用户或会话超时)

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)

这篇关于Symfony实例化服务一次,并与几个用户一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆