_factory" actually do? "/>

Re: What does "__PACKAGE__->_factory" actually do?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Quoted text here. Click to load it

You haven't said which class(es) this class inherits from, which makes
it hard to find the definition of ->_factory to see what it does.

Quoted text here. Click to load it
Quoted text here. Click to load it

This looks to me like the 'inside-out object' technique. The way this
works is that, instead of making your object a hashref and storing the
object's fields inside the object, store (say) all the id_of fields for
all objects of this class in one file-scoped %id_of hash, with the hash
keyed by the refaddr of the object this value belongs to.

That probably wasn't very clear, so an example might help. Here is a
class Foo with two fields 'bar' and 'baz':

    package Foo;

    use Scalar::Util qw/refaddr/;

    my %bar;
    my %baz;

    sub new {
        my ($class, %args) = @_;

        # In this case the object is an empty arrayref, but this is not
        # important. It can be any type blessed ref, since the fields
        # are not stored inside the object.
        my $self = bless [], $class;

        $bar{refaddr $self} = $args;
        $baz{refaddr $self} = $args;

    sub get_bar {
        my ($self) = @_;
        return $bar{refaddr $self};

    sub set_bar {
        my ($self, $new) = @_;
        $bar{refaddr $self} = $new;

    #...and equivalently for %baz

    # This is *really* important. Without this the entries in the hash
    # will never be cleared, and not only will they waste memory but it
    # is not unlikely another object will be allocated with the same
    # address, which would mean it would pick up fields which belonged
    # to a different object.
    sub DESTROY {
        my ($self) = @_;
        delete $bar{refaddr $self};
        delete $baz{refaddr $self};

A serious implementation ought to use Hash::Util::Fieldhash, which
correctly handles several nasty corner cases involving reblessing,
overloading and threads, as well as handling the garbage-collection for


Site Timeline