in reply to Re: Why not use a local variable for $self in Moose?
in thread Why not use a local variable for $self in Moose?

By the way, I'm glad I asked such a dumb question. Your mention of "singleton" finally shed some light for me on what a singleton might be used for. I never used them and wasn't quite sure why they might be used.

$PM = "Perl Monk's";
$MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest";
$nysus = $PM . ' ' . $MCF;
Click here if you love Perl Monks

  • Comment on Re^2: Why not use a local variable for $self in Moose?

Replies are listed 'Best First'.
Re^3: Why not use a local variable for $self in Moose?
by stevieb (Canon) on Oct 19, 2018 at 19:06 UTC

    I've got an example of where I use a singleton. It's a Dancer2 web application with a JS/jQuery front end. It has a separate module for the API, and one for DB.

    All users who view the page see the exact same results. When the page is updated on one device, it's auto-updated on all others as well.

    Both the API module (class) and DB module (class) are singletons (as is the log object). This ensures that each user loading the page are using the exact same object, so all configuration of the objects are consistent on all runs. If the DB or API objects modify themselves throughout the course of their duties, all instances of the application immediately have those attributes/changes provided.

    Here's some of the code from the API module:

    # the $api object is declared up here in file scope sub new { # return the stored object if we've already run new() if (defined $api){ $log->_5('returning stored API object'); return $api; } my $self = bless {}, shift; my $caller = (caller)[0]; $self->_args(@_, caller => $caller); warn "API in test mode\n" if $self->testing; $self->_init; $api = $self; $log->_5("successfully initialized the system"); if (! $self->testing && ! defined $events){ $self->events; $log->_5('successfully created new async events') } else { $log->_5("async events have already been spawned"); } return $self; }