Class::Singleton(3)

πŸ’– Class::Singleton β€” the manual page, but make it make sense πŸ’–

okay so real talk: this is the Class::Singleton(3) page from the user-contributed Perl docs (perl v5.42.0, dated 2025-02-06, if you're nosy like me πŸ‘€), and it's literally the whole "there can be only one" situation but for objects. stay with me bestie, it's gonna slay.


✨ NAME ✨

Class::Singleton β€” an implementation of a "Singleton" class. that's it. that's the whole vibe.


πŸ¦‹ SYNOPSIS πŸ¦‹

use Class::Singleton;

my $one = Class::Singleton->instance();   # returns a new instance
my $two = Class::Singleton->instance();   # returns same instance

see how $one and $two are the same thing? that's the entire point. iconic behavior fr fr πŸ’…


🌸 DESCRIPTION 🌸

So this is the Class::Singleton module, and a Singleton is basically an object class that can have, like, exactly one instance in any system. no more. no cap. think of examples like a print spooler or a system registry β€” the kind of thing where having two of them would be actual chaos 😭

This module implements a Singleton class, and other classes can be derived from it. On its own, Class::Singleton does genuinely very little β€” it's just there to manage the instantiation of a single object. The way it works is you derive your class from Class::Singleton, and your module inherits the Singleton instantiation method, and then you can implement literally whatever specific functionality you need on top of that. main character energy: the base class handles the "only one of me" thing, your class handles the rest πŸ’œ

If you want the full description and discussion of the Singleton class, go read "Design Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2. yeah, that's a real citation, we're being academic today πŸŽ€

🧚 Using the Class::Singleton Module

To import and use Class::Singleton, this line should appear in your Perl program:

use Class::Singleton;

The instance() method is what you use to create a new Class::Singleton instance, or to get a reference back to an existing one. And because of how it works, it is only possible to have a single instance of the class in any system. periodt.

my $highlander = Class::Singleton->instance();

Assuming no Class::Singleton object currently exists, this first call to instance() creates a new Class::Singleton and returns a reference to it. Future invocations of instance() will return that same reference. so chill of it.

my $macleod    = Class::Singleton->instance();

In the above example, both $highlander and $macleod contain the same reference to a Class::Singleton instance. There can be only one. βš”οΈ (the authors really did that, and honestly? respect.)

🫢 Deriving Singleton Classes

A module class may be derived from Class::Singleton, and it'll inherit the instance() method that correctly instantiates only one object. like so:

package PrintSpooler;
use base 'Class::Singleton';

# derived class specific code
sub submit_job {
    ...
}

sub cancel_job {
    ...
}

And the PrintSpooler class defined above could be used like this:

use PrintSpooler;

my $spooler = PrintSpooler->instance();

$spooler->submit_job(...);

Here's the lore: instance() calls the _new_instance() constructor method the first and only time a new instance is created. All parameters passed to the instance() method are forwarded to _new_instance(). In the base class, _new_instance() returns a blessed reference to a hash array containing any arguments passed as either a hash reference or a list of named parameters. slay.

package MyConfig;
use base 'Class::Singleton';

sub foo {
    shift->{ foo };
}

sub bar {
    shift->{ bar };
}

package main;

# either: hash reference of named parameters
my $config = MyConfig->instance({ foo => 10, bar => 20 });

# or: list of named parameters
my $config = MyConfig->instance( foo => 10, bar => 20 );

print $config->foo();   # 10
print $config->bar();   # 20

Derived classes may redefine the _new_instance() method to give you more specific object initialisation, or to change the underlying object type (to a list reference, for example). very much "customize your own adventure":

package MyApp::Database;
use base 'Class::Singleton';
use DBI;

# this only gets called the first time instance() is called
sub _new_instance {
    my $class = shift;
    my $self  = bless { }, $class;
    my $db    = shift || "myappdb";
    my $host  = shift || "localhost";

    $self->{ DB } = DBI->connect("DBI:mSQL:$db:$host")
        || die "Cannot connect to database: $DBI::errstr";

    # any other initialisation...

    return $self;
}

The above example might be used as follows:

use MyApp::Database;

# first use - database gets initialised
my $database = MyApp::Database->instance();

Some time later on in a module far, far away... 🌌

package MyApp::FooBar
use MyApp::Database;

# this FooBar object needs access to the database; the Singleton
# approach gives a nice wrapper around global variables.

sub new {
    my $class = shift;
    bless {
        database => MyApp::Database->instance(),
    }, $class;
}

The Class::Singleton instance() method uses a private hash to store a reference to any existing instance of the object, keyed against the derived class package name. lowkey clever ngl.

This means different classes can be derived from Class::Singleton and co-exist in the same system, while still only allowing one instance of any one class to exist. For example, it would be possible to derive both "PrintSpooler" and "MyApp::Database" from Class::Singleton and have a single instance of each in a system, rather than a single instance of either. one of each, not one total. big difference bestie πŸ’€

You can use the has_instance() method to find out if a particular class already has an instance defined. It returns a reference to the instance, or undef if none is currently defined.

my $instance = MyApp::Database->has_instance()
    || warn "No instance is defined yet";

πŸ‘‘ Methods

  • instance() β€” this method is called to return a current object instance, or to create a new one by calling _new_instance().
  • has_instance() β€” this method returns a reference to any existing instance, or undef if none is defined.
my $testing = MySingleton1->has_instance()
    || warn "No instance defined for MySingleton1";
  • _new_instance() β€” this "private" method gets called by instance() to create a new object instance if one doesn't already exist. It is not intended to be called directly (although, like, there's nothing actually stopping you from calling it if you're really determined to do so πŸ™ˆ).

It creates a blessed hash reference containing any arguments passed to the method as either a hash reference or a list of named parameters.

# either: hash reference of named parameters
my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });

# or: list of named parameters
my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );

It is important to remember that the instance() method will only call the _new_instance() method once, so any arguments you pass may be silently ignored if an instance already exists. that's the trap, bestie 😭 you can use the has_instance() method to determine if an instance is already defined β€” please do that instead of wondering why your args vanished.


πŸ“ EXPORTS πŸ“

None. nothing. zero. empty. a whole lot of nothing πŸ’…


πŸ’€ KNOWN BUGS πŸ’€

None. (iconic, honestly β€” we love a clean slate ✨)


🌈 FEEDBACK 🌈

Patches, bug reports, suggestions or any other feedback is welcome. they genuinely want to hear from you 🫢

Patches can be sent as GitHub pull requests at <https://github.com/steve-m-hay/Class-Singleton/pulls>.

Bug reports and suggestions can be made on the CPAN Request Tracker at <https://rt.cpan.org/Public/Bug/Report.html?Queue=Class-Singleton>.

Currently active requests on the CPAN Request Tracker can be viewed at <https://rt.cpan.org/Public/Dist/Display.html?Status=Active;Queue=Class-Singleton>.

Please test this distribution. See CPAN Testers Reports at <https://www.cpantesters.org/> for details of how to get involved. (yes, actually test it. do it for the culture 🧚)

Previous test results on CPAN Testers Reports can be viewed at <https://www.cpantesters.org/distro/C/Class-Singleton.html>.

Please rate this distribution on CPAN Ratings at <https://cpanratings.perl.org/rate/?distribution=Class-Singleton>. go leave a rating, it's free and it's kind ⭐


πŸ¦‹ AVAILABILITY πŸ¦‹

The latest version of this module is available from CPAN (see "CPAN" in perlmodlib for details) at

<https://metacpan.org/release/Class-Singleton> or

<https://www.cpan.org/authors/id/S/SH/SHAY/> or

<https://www.cpan.org/modules/by-module/Class/>.

The latest source code is available from GitHub at <https://github.com/steve-m-hay/Class-Singleton>.


πŸŽ€ INSTALLATION πŸŽ€

See the INSTALL file. (short and sweet, we love that for us)


πŸ’œ AUTHOR πŸ’œ

Andy Wardley <abw@wardley.org <mailto:abw@wardley.org>> <http://wardley.org/>.

Thanks to Andreas Koenig for providing some significant speedup patches and other ideas. king behavior πŸ”₯

Steve Hay <shay@cpan.org <mailto:shay@cpan.org>> is now maintaining Class::Singleton as of version 1.5.


Copyright (C) 1998 Canon Research Centre Europe Ltd.

Copyright (C) 1998-2008 Andy Wardley. All rights reserved.

Copyright (C) 2014, 2020 Steve Hay. All rights reserved.


⭐ LICENCE ⭐

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself, i.e. under the terms of either the GNU General Public License or the Artistic License, as specified in the LICENCE file.


🧚 VERSION 🧚

Version 1.6


πŸŽ€ DATE πŸŽ€

02 Dec 2020


πŸ’… HISTORY πŸ’…

See the Changes file. the lore is documented, go read it πŸ“–


ok that's the whole page, every flag-free, option-free, singleton-fueled detail intact πŸ’– now go forth and make exactly one instance of something. and remember: there can be only one 🫢✨

mwah β€” this was Class::Singleton(3) from the user-contributed Perl docs, Version 1.6, dated 02 Dec 2020, rendered here with the perl v5.42.0 / 2025-02-06 footer energy. bye bestie, see you in the next manpage πŸ’œπŸŽ€

πŸ“¦ where this page comes from