The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

PurpleWiki::Singleton - Enables the Singleton Pattern.

SYNOPSIS

    #!/usr/bin/perl
    use strict;
    use warnings;

    package PurpleWiki::SomeClass;
    use strict;
    use warnings;
    use base qw(PurpleWiki::Singleton);

    sub new {
        my $prototype = shift;
        my $class = ref($prototype) || $prototype;
        my $self = bless({ @_ }, $class);

        $class->setInstance($self);
        return $self;
    }

    sub test {
        my $self = shift;
        print $self->{test}, "\n";
    }
    1;

    package main;
    use strict;
    use warnings;

    my $obj = new PurpleWiki::SomeClass(test => "hello world");
    my $obj2 = PurpleWiki::SomeClass->instance();

    $obj->test();    # Prints hello world
    $obj2->test();   # Prints hello world

DESCRIPTION

PurpleWiki::Singleton is a virtual base class for enabling the Singleton pattern in classes that derive from it. It is safe to use both for stand alone modules and ones which persist in memory via mod_perl.

OBJECT STATE

_singletonObjectInstance

If used without mod_perl then the derived class will have the global variable _singletonObjectInstance inserted into its namespace. Nothing is inserted in a class's namespace if its used under mod_perl, so don't rely on this being there and don't be surprised if it is there.

CLASS METHODS

Class methods can only be called on the class and not on an object instance. This means you must provide the full package name followd by -> and then the method name. For example: PurpleWiki::Singleton->instance();

instance()

Returns the last instance of the class saved by setInstance(). If no such instance exists then undef is returned.

setInstance()

Sets the current instance of the class to be returned by instance().

AUTHORS

Matthew O'Connor, <matthew@canonical.org>

SEE ALSO

Apache::Singleton

PurpleWiki::Singleton was derived in large part on the equivalent Apache module. However, the simplicity of the task and the burden of a module dependancy ruled out using Apache::Singleton.