4

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.

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. It's my first post here, by the way, so I apologize for any shortcomings my question may have.

serenesat
  • 4,611
  • 10
  • 37
  • 53
Joe
  • 43
  • 3
  • 1
    Hi @Joe, your description sound like you are looking for a way to log messages ... if so, please have a look at all those fancy modules `Dancer2::Logger::*` that are available... if not, then it is certainly the wrong way when you are trying to pass stuff around. – vanHoesel Jan 20 '19 at 16:59
  • Hi @vanHoesel, thank you. But I want my libraries to be completely dancer2 agnostic. In fact, I am implementing an API I want to also use independently from dancer2, as ysth correctly assumed in his answer. – Joe Jan 21 '19 at 21:05

1 Answers1

6

It looks to me like you could use a var to hold your object.

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

ysth
  • 96,171
  • 6
  • 121
  • 214
  • so `var` is a request-scoped object ( a hash reference, if I remember the output of `Data::Dumper` well). This would make sense. I will try it once I have access to my dev environment again and report back. Hopefully tomorrow. Regarding weak references: Never used them and only now - inspired by your post - I read about them. Thanks - and as I said: I'll report back. – Joe Jan 21 '19 at 20:55
  • Using a var as a reference to the entry point of my API does exactly what I want: var API => AMS2::API->new; and later in my routes I use: del '/record/:id' => sub { vars->{API}->do_what_needs_to_be_done(route_parameters->get('id')); } Best, Joe – Joe Jan 22 '19 at 21:11