简体   繁体   English

如何创建仅在一个请求期间全局的“全局”范围变量?

[英]How to create 'globally' scoped variables that are global only during one request?

When a request hits my dancer2 app I want to set up an object that is accessible by all packages involved in handling this request. 当请求到达我的dancer2应用程序时,我想设置一个对象,该对象可以被处理此请求所涉及的所有包访问。

How can I make sure that this object has a scope only within this individual request and is not accessible by other requests? 如何确保此对象仅在此单个请求中具有范围,并且其他请求无法访问该对象?

Specifically this object should be filled with messages of all kinds (errors, warnings, debug messages, etc.) as execution travels through my libraries. 具体来说,当执行通过我的库时,此对象应填充各种消息(错误,警告,调试消息等)。

Obviously, those messages are request-specific and I am afraid that naively declaring a global reference to this message object is exposing it to all requests hitting the app. 显然,这些消息是特定于请求的,我担心天真地声明对此消息对象的全局引用会将其暴露给所有命中应用程序的请求。

I was thinking about creating an instance of this message class in the router and then passing a reference to it throughout all methods involved in handling this request. 我正在考虑在路由器中创建此消息类的实例,然后在处理此请求所涉及的所有方法中传递对它的引用。

My gut feeling tells me that I am missing something fundamentally here architecture-wise regarding dancer2, so I decided to ask you. 我的直觉告诉我,我在这里基本上缺少一些关于dancer2的建筑方面的东西,所以我决定问你。 It's my first post here, by the way, so I apologize for any shortcomings my question may have. 顺便说一下,这是我的第一篇文章,所以我为我的问题可能存在的任何缺点道歉。

It looks to me like you could use a var to hold your object. 在我看来,你可以使用var来保存你的对象。

See https://metacpan.org/pod/distribution/Dancer2/lib/Dancer2/Manual.pod#var 请参阅https://metacpan.org/pod/distribution/Dancer2/lib/Dancer2/Manual.pod#var

If you need it to be accessible even from methods that aren't aware of Dancer, you could use a var and also store your object in a global variable using a weak reference. 如果您需要甚至可以从不了解Dancer的方法访问它,您可以使用var并使用弱引用将对象存储在全局变量中。

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

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