eaiovnaovbqoebvqoeavibavo PKuiZz= 5.003_95); my $print = 0; sub printem { if (@_) { $print = shift } else { $print++ } } { package Class::Struct::Tie_ISA; sub TIEARRAY { my $class = shift; return bless [], $class; } sub STORE { my ($self, $index, $value) = @_; Class::Struct::_subclass_error(); } sub FETCH { my ($self, $index) = @_; $self->[$index]; } sub FETCHSIZE { my $self = shift; return scalar(@$self); } sub DESTROY { } } sub import { my $self = shift; if ( @_ == 0 ) { $self->export_to_level( 1, $self, @EXPORT ); } elsif ( @_ == 1 ) { # This is admittedly a little bit silly: # do we ever export anything else than 'struct'...? $self->export_to_level( 1, $self, @_ ); } else { goto &struct; } } sub struct { # Determine parameter list structure, one of: # struct( class => [ element-list ]) # struct( class => { element-list }) # struct( element-list ) # Latter form assumes current package name as struct name. my ($class, @decls); my $base_type = ref $_[1]; if ( $base_type eq 'HASH' ) { $class = shift; @decls = %{shift()}; _usage_error() if @_; } elsif ( $base_type eq 'ARRAY' ) { $class = shift; @decls = @{shift()}; _usage_error() if @_; } else { $base_type = 'ARRAY'; $class = (caller())[0]; @decls = @_; } _usage_error() if @decls % 2 == 1; # Ensure we are not, and will not be, a subclass. my $isa = do { no strict 'refs'; \@{$class . '::ISA'}; }; _subclass_error() if @$isa; tie @$isa, 'Class::Struct::Tie_ISA'; # Create constructor. croak "function 'new' already defined in package $class" if do { no strict 'refs'; defined &{$class . "::new"} }; my @methods = (); my %refs = (); my %arrays = (); my %hashes = (); my %classes = (); my $got_class = 0; my $out = ''; $out = "{\n package $class;\n use Carp;\n sub new {\n"; $out .= " my (\$class, \%init) = \@_;\n"; $out .= " \$class = __PACKAGE__ unless \@_;\n"; my $cnt = 0; my $idx = 0; my( $cmt, $name, $type, $elem ); if( $base_type eq 'HASH' ){ $out .= " my(\$r) = {};\n"; $cmt = ''; } elsif( $base_type eq 'ARRAY' ){ $out .= " my(\$r) = [];\n"; } while( $idx < @decls ){ $name = $decls[$idx]; $type = $decls[$idx+1]; push( @methods, $name ); if( $base_type eq 'HASH' ){ $elem = "{'${class}::$name'}"; } elsif( $base_type eq 'ARRAY' ){ $elem = "[$cnt]"; ++$cnt; $cmt = " # $name"; } if( $type =~ /^\*(.)/ ){ $refs{$name}++; $type = $1; } my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :"; if( $type eq '@' ){ $out .= " croak 'Initializer for $name must be array reference'\n"; $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n"; $out .= " \$r->$elem = $init [];$cmt\n"; $arrays{$name}++; } elsif( $type eq '%' ){ $out .= " croak 'Initializer for $name must be hash reference'\n"; $out .= " if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n"; $out .= " \$r->$elem = $init {};$cmt\n"; $hashes{$name}++; } elsif ( $type eq '$') { $out .= " \$r->$elem = $init undef;$cmt\n"; } elsif( $type =~ /^\w+(?:::\w+)*$/ ){ $out .= " if (defined(\$init{'$name'})) {\n"; $out .= " if (ref \$init{'$name'} eq 'HASH')\n"; $out .= " { \$r->$elem = $type->new(\%{\$init{'$name'}}) } $cmt\n"; $out .= " elsif (UNIVERSAL::isa(\$init{'$name'}, '$type'))\n"; $out .= " { \$r->$elem = \$init{'$name'} } $cmt\n"; $out .= " else { croak 'Initializer for $name must be hash or $type reference' }\n"; $out .= " }\n"; $classes{$name} = $type; $got_class = 1; } else{ croak "'$type' is not a valid struct element type"; } $idx += 2; } $out .= " bless \$r, \$class;\n }\n"; # Create accessor methods. my( $pre, $pst, $sel ); $cnt = 0; foreach $name (@methods){ if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) { warnings::warnif("function '$name' already defined, overrides struct accessor method"); } else { $pre = $pst = $cmt = $sel = ''; if( defined $refs{$name} ){ $pre = "\\("; $pst = ")"; $cmt = " # returns ref"; } $out .= " sub $name {$cmt\n my \$r = shift;\n"; if( $base_type eq 'ARRAY' ){ $elem = "[$cnt]"; ++$cnt; } elsif( $base_type eq 'HASH' ){ $elem = "{'${class}::$name'}"; } if( defined $arrays{$name} ){ $out .= " my \$i;\n"; $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n"; $out .= " if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n"; $sel = "->[\$i]"; } elsif( defined $hashes{$name} ){ $out .= " my \$i;\n"; $out .= " \@_ ? (\$i = shift) : return \$r->$elem;\n"; $out .= " if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n"; $sel = "->{\$i}"; } elsif( defined $classes{$name} ){ if ( $CHECK_CLASS_MEMBERSHIP ) { $out .= " croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n"; } } $out .= " croak 'Too many args to $name' if \@_ > 1;\n"; $out .= " \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n"; $out .= " }\n"; } } $out .= "}\n1;\n"; print $out if $print; my $result = eval $out; carp $@ if $@; } sub _usage_error { confess "struct usage error"; } sub _subclass_error { croak 'struct class cannot be a subclass (@ISA not allowed)'; } 1; # for require __END__ =head1 NAME Class::Struct - declare struct-like datatypes as Perl classes =head1 SYNOPSIS use Class::Struct; # declare struct, based on array: struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]); # declare struct, based on hash: struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... }); package CLASS_NAME; use Class::Struct; # declare struct, based on array, implicit class name: struct( ELEMENT_NAME => ELEMENT_TYPE, ... ); # Declare struct at compile time use Class::Struct CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]; use Class::Struct CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... }; # declare struct at compile time, based on array, implicit class name: package CLASS_NAME; use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ; package Myobj; use Class::Struct; # declare struct with four types of elements: struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' ); $obj = new Myobj; # constructor # scalar type accessor: $element_value = $obj->s; # element value $obj->s('new value'); # assign to element # array type accessor: $ary_ref = $obj->a; # reference to whole array $ary_element_value = $obj->a(2); # array element value $obj->a(2, 'new value'); # assign to array element # hash type accessor: $hash_ref = $obj->h; # reference to whole hash $hash_element_value = $obj->h('x'); # hash element value $obj->h('x', 'new value'); # assign to hash element # class type accessor: $element_value = $obj->c; # object reference $obj->c->method(...); # call method of object $obj->c(new My_Other_Class); # assign a new object =head1 DESCRIPTION C exports a single function, C. Given a list of element names and types, and optionally a class name, C creates a Perl 5 class that implements a "struct-like" data structure. The new class is given a constructor method, C, for creating struct objects. Each element in the struct data has an accessor method, which is used to assign to the element and to fetch its value. The default accessor can be overridden by declaring a C of the same name in the package. (See Example 2.) Each element's type can be scalar, array, hash, or class. =head2 The C function The C function has three forms of parameter-list. struct( CLASS_NAME => [ ELEMENT_LIST ]); struct( CLASS_NAME => { ELEMENT_LIST }); struct( ELEMENT_LIST ); The first and second forms explicitly identify the name of the class being created. The third form assumes the current package name as the class name. An object of a class created by the first and third forms is based on an array, whereas an object of a class created by the second form is based on a hash. The array-based forms will be somewhat faster and smaller; the hash-based forms are more flexible. The class created by C must not be a subclass of another class other than C. It can, however, be used as a superclass for other classes. To facilitate this, the generated constructor method uses a two-argument blessing. Furthermore, if the class is hash-based, the key of each element is prefixed with the class name (see I, Recipe 13.12). A function named C must not be explicitly defined in a class created by C. The I has the form NAME => TYPE, ... Each name-type pair declares one element of the struct. Each element name will be defined as an accessor method unless a method by that name is explicitly defined; in the latter case, a warning is issued if the warning flag (B<-w>) is set. =head2 Class Creation at Compile Time C can create your class at compile time. The main reason for doing this is obvious, so your class acts like every other class in Perl. Creating your class at compile time will make the order of events similar to using any other class ( or Perl module ). There is no significant speed gain between compile time and run time class creation, there is just a new, more standard order of events. =head2 Element Types and Accessor Methods The four element types -- scalar, array, hash, and class -- are represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name -- optionally preceded by a C<'*'>. The accessor method provided by C for an element depends on the declared type of the element. =over 4 =item Scalar (C<'$'> or C<'*$'>) The element is a scalar, and by default is initialized to C (but see L). The accessor's argument, if any, is assigned to the element. If the element type is C<'$'>, the value of the element (after assignment) is returned. If the element type is C<'*$'>, a reference to the element is returned. =item Array (C<'@'> or C<'*@'>) The element is an array, initialized by default to C<()>. With no argument, the accessor returns a reference to the element's whole array (whether or not the element was specified as C<'@'> or C<'*@'>). With one or two arguments, the first argument is an index specifying one element of the array; the second argument, if present, is assigned to the array element. If the element type is C<'@'>, the accessor returns the array element value. If the element type is C<'*@'>, a reference to the array element is returned. As a special case, when the accessor is called with an array reference as the sole argument, this causes an assignment of the whole array element. The object reference is returned. =item Hash (C<'%'> or C<'*%'>) The element is a hash, initialized by default to C<()>. With no argument, the accessor returns a reference to the element's whole hash (whether or not the element was specified as C<'%'> or C<'*%'>). With one or two arguments, the first argument is a key specifying one element of the hash; the second argument, if present, is assigned to the hash element. If the element type is C<'%'>, the accessor returns the hash element value. If the element type is C<'*%'>, a reference to the hash element is returned. As a special case, when the accessor is called with a hash reference as the sole argument, this causes an assignment of the whole hash element. The object reference is returned. =item Class (C<'Class_Name'> or C<'*Class_Name'>) The element's value must be a reference blessed to the named class or to one of its subclasses. The element is not initialized by default. The accessor's argument, if any, is assigned to the element. The accessor will C if this is not an appropriate object reference. If the element type does not start with a C<'*'>, the accessor returns the element value (after assignment). If the element type starts with a C<'*'>, a reference to the element itself is returned. =back =head2 Initializing with C C always creates a constructor called C. That constructor may take a list of initializers for the various elements of the new struct. Each initializer is a pair of values: IC< =E >I. The initializer value for a scalar element is just a scalar value. The initializer for an array element is an array reference. The initializer for a hash is a hash reference. The initializer for a class element is an object of the corresponding class, or of one of it's subclasses, or a reference to a hash containing named arguments to be passed to the element's constructor. See Example 3 below for an example of initialization. =head1 EXAMPLES =over 4 =item Example 1 Giving a struct element a class type that is also a struct is how structs are nested. Here, C represents a time (seconds and microseconds), and C has two elements, each of which is of type C. use Class::Struct; struct( Rusage => { ru_utime => 'Timeval', # user time used ru_stime => 'Timeval', # system time used }); struct( Timeval => [ tv_secs => '$', # seconds tv_usecs => '$', # microseconds ]); # create an object: my $t = Rusage->new(ru_utime=>Timeval->new(), ru_stime=>Timeval->new()); # $t->ru_utime and $t->ru_stime are objects of type Timeval. # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec. $t->ru_utime->tv_secs(100); $t->ru_utime->tv_usecs(0); $t->ru_stime->tv_secs(5); $t->ru_stime->tv_usecs(0); =item Example 2 An accessor function can be redefined in order to provide additional checking of values, etc. Here, we want the C element always to be nonnegative, so we redefine the C accessor accordingly. package MyObj; use Class::Struct; # declare the struct struct ( 'MyObj', { count => '$', stuff => '%' } ); # override the default accessor method for 'count' sub count { my $self = shift; if ( @_ ) { die 'count must be nonnegative' if $_[0] < 0; $self->{'MyObj::count'} = shift; warn "Too many args to count" if @_; } return $self->{'MyObj::count'}; } package main; $x = new MyObj; print "\$x->count(5) = ", $x->count(5), "\n"; # prints '$x->count(5) = 5' print "\$x->count = ", $x->count, "\n"; # prints '$x->count = 5' print "\$x->count(-5) = ", $x->count(-5), "\n"; # dies due to negative argument! =item Example 3 The constructor of a generated class can be passed a list of I=>I pairs, with which to initialize the struct. If no initializer is specified for a particular element, its default initialization is performed instead. Initializers for non-existent elements are silently ignored. Note that the initializer for a nested class may be specified as an object of that class, or as a reference to a hash of initializers that are passed on to the nested struct's constructor. use Class::Struct; struct Breed => { name => '$', cross => '$', }; struct Cat => [ name => '$', kittens => '@', markings => '%', breed => 'Breed', ]; my $cat = Cat->new( name => 'Socks', kittens => ['Monica', 'Kenneth'], markings => { socks=>1, blaze=>"white" }, breed => Breed->new(name=>'short-hair', cross=>1), or: breed => {name=>'short-hair', cross=>1}, ); print "Once a cat called ", $cat->name, "\n"; print "(which was a ", $cat->breed->name, ")\n"; print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n"; =back =head1 Author and Modification History Modified by Damian Conway, 2001-09-10, v0.62. Modified implicit construction of nested objects. Now will also take an object ref instead of requiring a hash ref. Also default initializes nested object attributes to undef, rather than calling object constructor without args Original over-helpfulness was fraught with problems: * the class's constructor might not be called 'new' * the class might not have a hash-like-arguments constructor * the class might not have a no-argument constructor * "recursive" data structures didn't work well: package Person; struct { mother => 'Person', father => 'Person'}; Modified by Casey West, 2000-11-08, v0.59. Added the ability for compile time class creation. Modified by Damian Conway, 1999-03-05, v0.58. Added handling of hash-like arg list to class ctor. Changed to two-argument blessing in ctor to support derivation from created classes. Added classname prefixes to keys in hash-based classes (refer to "Perl Cookbook", Recipe 13.12 for rationale). Corrected behaviour of accessors for '*@' and '*%' struct elements. Package now implements documented behaviour when returning a reference to an entire hash or array element. Previously these were returned as a reference to a reference to the element. Renamed to C and modified by Jim Miner, 1997-04-02. members() function removed. Documentation corrected and extended. Use of struct() in a subclass prohibited. User definition of accessor allowed. Treatment of '*' in element types corrected. Treatment of classes as element types corrected. Class name to struct() made optional. Diagnostic checks added. Originally C by Dean Roehrich. # Template.pm --- struct/member template builder # 12mar95 # Dean Roehrich # # changes/bugs fixed since 28nov94 version: # - podified # changes/bugs fixed since 21nov94 version: # - Fixed examples. # changes/bugs fixed since 02sep94 version: # - Moved to Class::Template. # changes/bugs fixed since 20feb94 version: # - Updated to be a more proper module. # - Added "use strict". # - Bug in build_methods, was using @var when @$var needed. # - Now using my() rather than local(). # # Uses perl5 classes to create nested data types. # This is offered as one implementation of Tom Christiansen's "structs.pl" # idea. =cut PK iZ%PP Accessor.pmnu[package Class::Accessor; require 5.00502; use strict; $Class::Accessor::VERSION = '0.34'; sub new { my($proto, $fields) = @_; my($class) = ref $proto || $proto; $fields = {} unless defined $fields; # make a copy of $fields. bless {%$fields}, $class; } sub mk_accessors { my($self, @fields) = @_; $self->_mk_accessors('rw', @fields); } if (eval { require Sub::Name }) { Sub::Name->import; } { no strict 'refs'; sub import { my ($class, @what) = @_; my $caller = caller; for (@what) { if (/^(?:antlers|moose-?like)$/i) { *{"${caller}::has"} = sub { my ($f, %args) = @_; $caller->_mk_accessors(($args{is}||"rw"), $f); }; *{"${caller}::extends"} = sub { @{"${caller}::ISA"} = @_; unless (grep $_->can("_mk_accessors"), @_) { push @{"${caller}::ISA"}, $class; } }; # we'll use their @ISA as a default, in case it happens to be # set already &{"${caller}::extends"}(@{"${caller}::ISA"}); } } } sub follow_best_practice { my($self) = @_; my $class = ref $self || $self; *{"${class}::accessor_name_for"} = \&best_practice_accessor_name_for; *{"${class}::mutator_name_for"} = \&best_practice_mutator_name_for; } sub _mk_accessors { my($self, $access, @fields) = @_; my $class = ref $self || $self; my $ra = $access eq 'rw' || $access eq 'ro'; my $wa = $access eq 'rw' || $access eq 'wo'; foreach my $field (@fields) { my $accessor_name = $self->accessor_name_for($field); my $mutator_name = $self->mutator_name_for($field); if( $accessor_name eq 'DESTROY' or $mutator_name eq 'DESTROY' ) { $self->_carp("Having a data accessor named DESTROY in '$class' is unwise."); } if ($accessor_name eq $mutator_name) { my $accessor; if ($ra && $wa) { $accessor = $self->make_accessor($field); } elsif ($ra) { $accessor = $self->make_ro_accessor($field); } else { $accessor = $self->make_wo_accessor($field); } my $fullname = "${class}::$accessor_name"; my $subnamed = 0; unless (defined &{$fullname}) { subname($fullname, $accessor) if defined &subname; $subnamed = 1; *{$fullname} = $accessor; } if ($accessor_name eq $field) { # the old behaviour my $alias = "${class}::_${field}_accessor"; subname($alias, $accessor) if defined &subname and not $subnamed; *{$alias} = $accessor unless defined &{$alias}; } } else { my $fullaccname = "${class}::$accessor_name"; my $fullmutname = "${class}::$mutator_name"; if ($ra and not defined &{$fullaccname}) { my $accessor = $self->make_ro_accessor($field); subname($fullaccname, $accessor) if defined &subname; *{$fullaccname} = $accessor; } if ($wa and not defined &{$fullmutname}) { my $mutator = $self->make_wo_accessor($field); subname($fullmutname, $mutator) if defined &subname; *{$fullmutname} = $mutator; } } } } } sub mk_ro_accessors { my($self, @fields) = @_; $self->_mk_accessors('ro', @fields); } sub mk_wo_accessors { my($self, @fields) = @_; $self->_mk_accessors('wo', @fields); } sub best_practice_accessor_name_for { my ($class, $field) = @_; return "get_$field"; } sub best_practice_mutator_name_for { my ($class, $field) = @_; return "set_$field"; } sub accessor_name_for { my ($class, $field) = @_; return $field; } sub mutator_name_for { my ($class, $field) = @_; return $field; } sub set { my($self, $key) = splice(@_, 0, 2); if(@_ == 1) { $self->{$key} = $_[0]; } elsif(@_ > 1) { $self->{$key} = [@_]; } else { $self->_croak("Wrong number of arguments received"); } } sub get { my $self = shift; if(@_ == 1) { return $self->{$_[0]}; } elsif( @_ > 1 ) { return @{$self}{@_}; } else { $self->_croak("Wrong number of arguments received"); } } sub make_accessor { my ($class, $field) = @_; return sub { my $self = shift; if(@_) { return $self->set($field, @_); } else { return $self->get($field); } }; } sub make_ro_accessor { my($class, $field) = @_; return sub { my $self = shift; if (@_) { my $caller = caller; $self->_croak("'$caller' cannot alter the value of '$field' on objects of class '$class'"); } else { return $self->get($field); } }; } sub make_wo_accessor { my($class, $field) = @_; return sub { my $self = shift; unless (@_) { my $caller = caller; $self->_croak("'$caller' cannot access the value of '$field' on objects of class '$class'"); } else { return $self->set($field, @_); } }; } use Carp (); sub _carp { my ($self, $msg) = @_; Carp::carp($msg || $self); return; } sub _croak { my ($self, $msg) = @_; Carp::croak($msg || $self); return; } 1; __END__ =head1 NAME Class::Accessor - Automated accessor generation =head1 SYNOPSIS package Foo; use base qw(Class::Accessor); Foo->follow_best_practice; Foo->mk_accessors(qw(name role salary)); # or if you prefer a Moose-like interface... package Foo; use Class::Accessor "antlers"; has name => ( is => "rw", isa => "Str" ); has role => ( is => "rw", isa => "Str" ); has salary => ( is => "rw", isa => "Num" ); # Meanwhile, in a nearby piece of code! # Class::Accessor provides new(). my $mp = Foo->new({ name => "Marty", role => "JAPH" }); my $job = $mp->role; # gets $mp->{role} $mp->salary(400000); # sets $mp->{salary} = 400000 # I wish # like my @info = @{$mp}{qw(name role)} my @info = $mp->get(qw(name role)); # $mp->{salary} = 400000 $mp->set('salary', 400000); =head1 DESCRIPTION This module automagically generates accessors/mutators for your class. Most of the time, writing accessors is an exercise in cutting and pasting. You usually wind up with a series of methods like this: sub name { my $self = shift; if(@_) { $self->{name} = $_[0]; } return $self->{name}; } sub salary { my $self = shift; if(@_) { $self->{salary} = $_[0]; } return $self->{salary}; } # etc... One for each piece of data in your object. While some will be unique, doing value checks and special storage tricks, most will simply be exercises in repetition. Not only is it Bad Style to have a bunch of repetitious code, but it's also simply not lazy, which is the real tragedy. If you make your module a subclass of Class::Accessor and declare your accessor fields with mk_accessors() then you'll find yourself with a set of automatically generated accessors which can even be customized! The basic set up is very simple: package Foo; use base qw(Class::Accessor); Foo->mk_accessors( qw(far bar car) ); Done. Foo now has simple far(), bar() and car() accessors defined. Alternatively, if you want to follow Damian's I guidelines you can use: package Foo; use base qw(Class::Accessor); Foo->follow_best_practice; Foo->mk_accessors( qw(far bar car) ); B you must call C before calling C. =head2 Moose-like By popular demand we now have a simple Moose-like interface. You can now do: package Foo; use Class::Accessor "antlers"; has far => ( is => "rw" ); has bar => ( is => "rw" ); has car => ( is => "rw" ); Currently only the C attribute is supported. =head1 CONSTRUCTOR Class::Accessor provides a basic constructor, C. It generates a hash-based object and can be called as either a class method or an object method. =head2 new my $obj = Foo->new; my $obj = $other_obj->new; my $obj = Foo->new(\%fields); my $obj = $other_obj->new(\%fields); It takes an optional %fields hash which is used to initialize the object (handy if you use read-only accessors). The fields of the hash correspond to the names of your accessors, so... package Foo; use base qw(Class::Accessor); Foo->mk_accessors('foo'); my $obj = Foo->new({ foo => 42 }); print $obj->foo; # 42 however %fields can contain anything, new() will shove them all into your object. =head1 MAKING ACCESSORS =head2 follow_best_practice In Damian's Perl Best Practices book he recommends separate get and set methods with the prefix set_ and get_ to make it explicit what you intend to do. If you want to create those accessor methods instead of the default ones, call: __PACKAGE__->follow_best_practice B you call any of the accessor-making methods. =head2 accessor_name_for / mutator_name_for You may have your own crazy ideas for the names of the accessors, so you can make those happen by overriding C and C in your subclass. (I copied that idea from Class::DBI.) =head2 mk_accessors __PACKAGE__->mk_accessors(@fields); This creates accessor/mutator methods for each named field given in @fields. Foreach field in @fields it will generate two accessors. One called "field()" and the other called "_field_accessor()". For example: # Generates foo(), _foo_accessor(), bar() and _bar_accessor(). __PACKAGE__->mk_accessors(qw(foo bar)); See L for details. =head2 mk_ro_accessors __PACKAGE__->mk_ro_accessors(@read_only_fields); Same as mk_accessors() except it will generate read-only accessors (ie. true accessors). If you attempt to set a value with these accessors it will throw an exception. It only uses get() and not set(). package Foo; use base qw(Class::Accessor); Foo->mk_ro_accessors(qw(foo bar)); # Let's assume we have an object $foo of class Foo... print $foo->foo; # ok, prints whatever the value of $foo->{foo} is $foo->foo(42); # BOOM! Naughty you. =head2 mk_wo_accessors __PACKAGE__->mk_wo_accessors(@write_only_fields); Same as mk_accessors() except it will generate write-only accessors (ie. mutators). If you attempt to read a value with these accessors it will throw an exception. It only uses set() and not get(). B I'm not entirely sure why this is useful, but I'm sure someone will need it. If you've found a use, let me know. Right now it's here for orthoginality and because it's easy to implement. package Foo; use base qw(Class::Accessor); Foo->mk_wo_accessors(qw(foo bar)); # Let's assume we have an object $foo of class Foo... $foo->foo(42); # OK. Sets $self->{foo} = 42 print $foo->foo; # BOOM! Can't read from this accessor. =head1 Moose! If you prefer a Moose-like interface to create accessors, you can use C by importing this module like this: use Class::Accessor "antlers"; or use Class::Accessor "moose-like"; Then you can declare accessors like this: has alpha => ( is => "rw", isa => "Str" ); has beta => ( is => "ro", isa => "Str" ); has gamma => ( is => "wo", isa => "Str" ); Currently only the C attribute is supported. And our C also supports the "wo" value to make a write-only accessor. If you are using the Moose-like interface then you should use the C rather than tweaking your C<@ISA> directly. Basically, replace @ISA = qw/Foo Bar/; with extends(qw/Foo Bar/); =head1 DETAILS An accessor generated by Class::Accessor looks something like this: # Your foo may vary. sub foo { my($self) = shift; if(@_) { # set return $self->set('foo', @_); } else { return $self->get('foo'); } } Very simple. All it does is determine if you're wanting to set a value or get a value and calls the appropriate method. Class::Accessor provides default get() and set() methods which your class can override. They're detailed later. =head2 Modifying the behavior of the accessor Rather than actually modifying the accessor itself, it is much more sensible to simply override the two key methods which the accessor calls. Namely set() and get(). If you -really- want to, you can override make_accessor(). =head2 set $obj->set($key, $value); $obj->set($key, @values); set() defines how generally one stores data in the object. override this method to change how data is stored by your accessors. =head2 get $value = $obj->get($key); @values = $obj->get(@keys); get() defines how data is retreived from your objects. override this method to change how it is retreived. =head2 make_accessor $accessor = __PACKAGE__->make_accessor($field); Generates a subroutine reference which acts as an accessor for the given $field. It calls get() and set(). If you wish to change the behavior of your accessors, try overriding get() and set() before you start mucking with make_accessor(). =head2 make_ro_accessor $read_only_accessor = __PACKAGE__->make_ro_accessor($field); Generates a subroutine refrence which acts as a read-only accessor for the given $field. It only calls get(). Override get() to change the behavior of your accessors. =head2 make_wo_accessor $read_only_accessor = __PACKAGE__->make_wo_accessor($field); Generates a subroutine refrence which acts as a write-only accessor (mutator) for the given $field. It only calls set(). Override set() to change the behavior of your accessors. =head1 EXCEPTIONS If something goes wrong Class::Accessor will warn or die by calling Carp::carp or Carp::croak. If you don't like this you can override _carp() and _croak() in your subclass and do whatever else you want. =head1 EFFICIENCY Class::Accessor does not employ an autoloader, thus it is much faster than you'd think. Its generated methods incur no special penalty over ones you'd write yourself. accessors: Rate Basic Fast Faster Direct Basic 367589/s -- -51% -55% -89% Fast 747964/s 103% -- -9% -77% Faster 819199/s 123% 10% -- -75% Direct 3245887/s 783% 334% 296% -- mutators: Rate Acc Fast Faster Direct Acc 265564/s -- -54% -63% -91% Fast 573439/s 116% -- -21% -80% Faster 724710/s 173% 26% -- -75% Direct 2860979/s 977% 399% 295% -- Class::Accessor::Fast is faster than methods written by an average programmer (where "average" is based on Schwern's example code). Class::Accessor is slower than average, but more flexible. Class::Accessor::Faster is even faster than Class::Accessor::Fast. It uses an array internally, not a hash. This could be a good or bad feature depending on your point of view. Direct hash access is, of course, much faster than all of these, but it provides no encapsulation. Of course, it's not as simple as saying "Class::Accessor is slower than average". These are benchmarks for a simple accessor. If your accessors do any sort of complicated work (such as talking to a database or writing to a file) the time spent doing that work will quickly swamp the time spend just calling the accessor. In that case, Class::Accessor and the ones you write will be roughly the same speed. =head1 EXAMPLES Here's an example of generating an accessor for every public field of your class. package Altoids; use base qw(Class::Accessor Class::Fields); use fields qw(curiously strong mints); Altoids->mk_accessors( Altoids->show_fields('Public') ); sub new { my $proto = shift; my $class = ref $proto || $proto; return fields::new($class); } my Altoids $tin = Altoids->new; $tin->curiously('Curiouser and curiouser'); print $tin->{curiously}; # prints 'Curiouser and curiouser' # Subclassing works, too. package Mint::Snuff; use base qw(Altoids); my Mint::Snuff $pouch = Mint::Snuff->new; $pouch->strong('Blow your head off!'); print $pouch->{strong}; # prints 'Blow your head off!' Here's a simple example of altering the behavior of your accessors. package Foo; use base qw(Class::Accessor); Foo->mk_accessors(qw(this that up down)); sub get { my $self = shift; # Note every time someone gets some data. print STDERR "Getting @_\n"; $self->SUPER::get(@_); } sub set { my ($self, $key) = splice(@_, 0, 2); # Note every time someone sets some data. print STDERR "Setting $key to @_\n"; $self->SUPER::set($key, @_); } =head1 CAVEATS AND TRICKS Class::Accessor has to do some internal wackiness to get its job done quickly and efficiently. Because of this, there's a few tricks and traps one must know about. Hey, nothing's perfect. =head2 Don't make a field called DESTROY This is bad. Since DESTROY is a magical method it would be bad for us to define an accessor using that name. Class::Accessor will carp if you try to use it with a field named "DESTROY". =head2 Overriding autogenerated accessors You may want to override the autogenerated accessor with your own, yet have your custom accessor call the default one. For instance, maybe you want to have an accessor which checks its input. Normally, one would expect this to work: package Foo; use base qw(Class::Accessor); Foo->mk_accessors(qw(email this that whatever)); # Only accept addresses which look valid. sub email { my($self) = shift; my($email) = @_; if( @_ ) { # Setting require Email::Valid; unless( Email::Valid->address($email) ) { carp("$email doesn't look like a valid address."); return; } } return $self->SUPER::email(@_); } There's a subtle problem in the last example, and it's in this line: return $self->SUPER::email(@_); If we look at how Foo was defined, it called mk_accessors() which stuck email() right into Foo's namespace. There *is* no SUPER::email() to delegate to! Two ways around this... first is to make a "pure" base class for Foo. This pure class will generate the accessors and provide the necessary super class for Foo to use: package Pure::Organic::Foo; use base qw(Class::Accessor); Pure::Organic::Foo->mk_accessors(qw(email this that whatever)); package Foo; use base qw(Pure::Organic::Foo); And now Foo::email() can override the generated Pure::Organic::Foo::email() and use it as SUPER::email(). This is probably the most obvious solution to everyone but me. Instead, what first made sense to me was for mk_accessors() to define an alias of email(), _email_accessor(). Using this solution, Foo::email() would be written with: return $self->_email_accessor(@_); instead of the expected SUPER::email(). =head1 AUTHORS Copyright 2009 Marty Pauley This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. That means either (a) the GNU General Public License or (b) the Artistic License. =head2 ORIGINAL AUTHOR Michael G Schwern =head2 THANKS Liz and RUZ for performance tweaks. Tels, for his big feature request/bug report. Various presenters at YAPC::Asia 2009 for criticising the non-Moose interface. =head1 SEE ALSO See L and L if speed is more important than flexibility. These are some modules which do similar things in different ways L, L, L, L, L, L, L See L for an example of this module in use. =cut PK iZe.&.&Load.pmnu[package Class::Load; { $Class::Load::VERSION = '0.20'; } use strict; use warnings; use base 'Exporter'; use Data::OptList 'mkopt'; use Module::Implementation 0.04; use Module::Runtime 0.012 qw( check_module_name module_notional_filename require_module use_module ); use Try::Tiny; { my $loader = Module::Implementation::build_loader_sub( implementations => [ 'XS', 'PP' ], symbols => ['is_class_loaded'], ); $loader->(); } our @EXPORT_OK = qw/load_class load_optional_class try_load_class is_class_loaded load_first_existing_class/; our %EXPORT_TAGS = ( all => \@EXPORT_OK, ); our $ERROR; sub load_class { my $class = shift; my $options = shift; my ($res, $e) = try_load_class($class, $options); return $class if $res; _croak($e); } sub load_first_existing_class { my $classes = Data::OptList::mkopt(\@_) or return; foreach my $class (@{$classes}) { check_module_name($class->[0]); } for my $class (@{$classes}) { my ($name, $options) = @{$class}; # We need to be careful not to pass an undef $options to this sub, # since the XS version will blow up if that happens. return $name if is_class_loaded($name, ($options ? $options : ())); my ($res, $e) = try_load_class($name, $options); return $name if $res; my $file = module_notional_filename($name); next if $e =~ /^Can't locate \Q$file\E in \@INC/; next if $options && defined $options->{-version} && $e =~ _version_fail_re($name, $options->{-version}); _croak("Couldn't load class ($name) because: $e"); } my @list = map { $_->[0] . ( $_->[1] && defined $_->[1]{-version} ? " (version >= $_->[1]{-version})" : q{} ) } @{$classes}; my $err .= q{Can't locate } . _or_list(@list) . " in \@INC (\@INC contains: @INC)."; _croak($err); } sub _version_fail_re { my $name = shift; my $vers = shift; return qr/\Q$name\E version \Q$vers\E required--this is only version/; } sub _nonexistent_fail_re { my $name = shift; my $file = module_notional_filename($name); return qr/Can't locate \Q$file\E in \@INC/; } sub _or_list { return $_[0] if @_ == 1; return join ' or ', @_ if @_ ==2; my $last = pop; my $list = join ', ', @_; $list .= ', or ' . $last; return $list; } sub load_optional_class { my $class = shift; my $options = shift; check_module_name($class); my ($res, $e) = try_load_class($class, $options); return 1 if $res; return 0 if $options && defined $options->{-version} && $e =~ _version_fail_re($class, $options->{-version}); return 0 if $e =~ _nonexistent_fail_re($class); _croak($e); } sub try_load_class { my $class = shift; my $options = shift; check_module_name($class); local $@; undef $ERROR; if (is_class_loaded($class)) { # We need to check this here rather than in is_class_loaded() because # we want to return the error message for a failed version check, but # is_class_loaded just returns true/false. return 1 unless $options && defined $options->{-version}; return try { $class->VERSION($options->{-version}); 1; } catch { _error($_); }; } my $file = module_notional_filename($class); # This says "our diagnostics of the package # say perl's INC status about the file being loaded are # wrong", so we delete it from %INC, so when we call require(), # perl will *actually* try reloading the file. # # If the file is already in %INC, it won't retry, # And on 5.8, it won't fail either! # # The extra benefit of this trick, is it helps even on # 5.10, as instead of dying with "Compilation failed", # it will die with the actual error, and thats a win-win. delete $INC{$file}; return try { local $SIG{__DIE__} = 'DEFAULT'; if ($options && defined $options->{-version}) { use_module($class, $options->{-version}); } else { require_module($class); } 1; } catch { _error($_); }; } sub _error { my $e = shift; $e =~ s/ at .+?Runtime\.pm line [0-9]+\.$//; chomp $e; $ERROR = $e; return 0 unless wantarray; return 0, $ERROR; } sub _croak { require Carp; local $Carp::CarpLevel = $Carp::CarpLevel + 2; Carp::croak(shift); } 1; # ABSTRACT: a working (require "Class::Name") and more =pod =head1 NAME Class::Load - a working (require "Class::Name") and more =head1 VERSION version 0.20 =head1 SYNOPSIS use Class::Load ':all'; try_load_class('Class::Name') or plan skip_all => "Class::Name required to run these tests"; load_class('Class::Name'); is_class_loaded('Class::Name'); my $baseclass = load_optional_class('Class::Name::MightExist') ? 'Class::Name::MightExist' : 'Class::Name::Default'; =head1 DESCRIPTION C only accepts C style module names, not C. How frustrating! For that, we provide C. It's often useful to test whether a module can be loaded, instead of throwing an error when it's not available. For that, we provide C. Finally, sometimes we need to know whether a particular class has been loaded. Asking C<%INC> is an option, but that will miss inner packages and any class for which the filename does not correspond to the package name. For that, we provide C. =head1 FUNCTIONS =head2 load_class Class::Name, \%options C will load C or throw an error, much like C. If C is already loaded (checked with C) then it will not try to load the class. This is useful when you have inner packages which C does not check. The C<%options> hash currently accepts one key, C<-version>. If you specify a version, then this subroutine will call C<< Class::Name->VERSION( $options{-version} ) >> internally, which will throw an error if the class's version is not equal to or greater than the version you requested. This method will return the name of the class on success. =head2 try_load_class Class::Name, \%options -> (0|1, error message) Returns 1 if the class was loaded, 0 if it was not. If the class was not loaded, the error will be returned as a second return value in list context. Again, if C is already loaded (checked with C) then it will not try to load the class. This is useful when you have inner packages which C does not check. Like C, you can pass a C<-version> in C<%options>. If the version is not sufficient, then this subroutine will return false. =head2 is_class_loaded Class::Name, \%options -> 0|1 This uses a number of heuristics to determine if the class C is loaded. There heuristics were taken from L's old pure-perl implementation. Like C, you can pass a C<-version> in C<%options>. If the version is not sufficient, then this subroutine will return false. =head2 load_first_existing_class Class::Name, \%options, ... This attempts to load the first loadable class in the list of classes given. Each class name can be followed by an options hash reference. If any one of the classes loads and passes the optional version check, that class name will be returned. If I of the classes can be loaded (or none pass their version check), then an error will be thrown. If, when attempting to load a class, it fails to load because of a syntax error, then an error will be thrown immediately. =head2 load_optional_class Class::Name, \%options -> 0|1 C is a lot like C, but also a lot like C. If the class exists, and it works, then it will return 1. If you specify a version in C<%options>, then the version check must succeed or it will return 0. If the class doesn't exist, and it appears to not exist on disk either, it will return 0. If the class exists on disk, but loading from disk results in an error ( i.e.: a syntax error ), then it will C with that error. This is useful for using if you want a fallback module system, i.e.: my $class = load_optional_class($foo) ? $foo : $default; That way, if $foo does exist, but can't be loaded due to error, you won't get the behaviour of it simply not existing. =head1 SEE ALSO =over 4 =item L This blog post is a good overview of the current state of the existing modules for loading other modules in various ways. =item L This blog post describes how to handle optional modules with L. =item L This Japanese blog post describes why L now uses L over its competitors. =item L, L, L, etc This module was designed to be used anywhere you have C, which occurs in many large projects. =back =head1 AUTHOR Shawn M Moore =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2012 by Shawn M Moore. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut __END__ PK iZұ|Accessor/Fast.pmnu[package Class::Accessor::Fast; use base 'Class::Accessor'; use strict; $Class::Accessor::Fast::VERSION = '0.34'; sub make_accessor { my($class, $field) = @_; return sub { return $_[0]->{$field} if scalar(@_) == 1; return $_[0]->{$field} = scalar(@_) == 2 ? $_[1] : [@_[1..$#_]]; }; } sub make_ro_accessor { my($class, $field) = @_; return sub { return $_[0]->{$field} if @_ == 1; my $caller = caller; $_[0]->_croak("'$caller' cannot alter the value of '$field' on objects of class '$class'"); }; } sub make_wo_accessor { my($class, $field) = @_; return sub { if (@_ == 1) { my $caller = caller; $_[0]->_croak("'$caller' cannot access the value of '$field' on objects of class '$class'"); } else { return $_[0]->{$field} = $_[1] if @_ == 2; return (shift)->{$field} = \@_; } }; } 1; __END__ =head1 NAME Class::Accessor::Fast - Faster, but less expandable, accessors =head1 SYNOPSIS package Foo; use base qw(Class::Accessor::Fast); # The rest is the same as Class::Accessor but without set() and get(). =head1 DESCRIPTION This is a faster but less expandable version of Class::Accessor. Class::Accessor's generated accessors require two method calls to accompish their task (one for the accessor, another for get() or set()). Class::Accessor::Fast eliminates calling set()/get() and does the access itself, resulting in a somewhat faster accessor. The downside is that you can't easily alter the behavior of your accessors, nor can your subclasses. Of course, should you need this later, you can always swap out Class::Accessor::Fast for Class::Accessor. Read the documentation for Class::Accessor for more info. =head1 EFFICIENCY L for an efficiency comparison. =head1 AUTHORS Copyright 2007 Marty Pauley This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. That means either (a) the GNU General Public License or (b) the Artistic License. =head2 ORIGINAL AUTHOR Michael G Schwern =head1 SEE ALSO L =cut PK iZ( Accessor/Faster.pmnu[package Class::Accessor::Faster; use base 'Class::Accessor'; use strict; $Class::Accessor::Faster::VERSION = '0.34'; my %slot; sub _slot { my($class, $field) = @_; my $n = $slot{$class}->{$field}; return $n if defined $n; $n = keys %{$slot{$class}}; $slot{$class}->{$field} = $n; return $n; } sub new { my($proto, $fields) = @_; my($class) = ref $proto || $proto; my $self = bless [], $class; $fields = {} unless defined $fields; for my $k (keys %$fields) { my $n = $class->_slot($k); $self->[$n] = $fields->{$k}; } return $self; } sub make_accessor { my($class, $field) = @_; my $n = $class->_slot($field); return sub { return $_[0]->[$n] if scalar(@_) == 1; return $_[0]->[$n] = scalar(@_) == 2 ? $_[1] : [@_[1..$#_]]; }; } sub make_ro_accessor { my($class, $field) = @_; my $n = $class->_slot($field); return sub { return $_[0]->[$n] if @_ == 1; my $caller = caller; $_[0]->_croak("'$caller' cannot alter the value of '$field' on objects of class '$class'"); }; } sub make_wo_accessor { my($class, $field) = @_; my $n = $class->_slot($field); return sub { if (@_ == 1) { my $caller = caller; $_[0]->_croak("'$caller' cannot access the value of '$field' on objects of class '$class'"); } else { return $_[0]->[$n] = $_[1] if @_ == 2; return (shift)->[$n] = \@_; } }; } 1; __END__ =head1 NAME Class::Accessor::Faster - Even faster, but less expandable, accessors =head1 SYNOPSIS package Foo; use base qw(Class::Accessor::Faster); =head1 DESCRIPTION This is a faster but less expandable version of Class::Accessor::Fast. Class::Accessor's generated accessors require two method calls to accompish their task (one for the accessor, another for get() or set()). Class::Accessor::Fast eliminates calling set()/get() and does the access itself, resulting in a somewhat faster accessor. Class::Accessor::Faster uses an array reference underneath to be faster. Read the documentation for Class::Accessor for more info. =head1 AUTHORS Copyright 2007 Marty Pauley This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. That means either (a) the GNU General Public License or (b) the Artistic License. =head1 SEE ALSO L =cut PK iZ t[Data/Inheritable.pmnu[package Class::Data::Inheritable; use strict qw(vars subs); use vars qw($VERSION); $VERSION = '0.08'; sub mk_classdata { my ($declaredclass, $attribute, $data) = @_; if( ref $declaredclass ) { require Carp; Carp::croak("mk_classdata() is a class method, not an object method"); } my $accessor = sub { my $wantclass = ref($_[0]) || $_[0]; return $wantclass->mk_classdata($attribute)->(@_) if @_>1 && $wantclass ne $declaredclass; $data = $_[1] if @_>1; return $data; }; my $alias = "_${attribute}_accessor"; *{$declaredclass.'::'.$attribute} = $accessor; *{$declaredclass.'::'.$alias} = $accessor; } 1; __END__ =head1 NAME Class::Data::Inheritable - Inheritable, overridable class data =head1 SYNOPSIS package Stuff; use base qw(Class::Data::Inheritable); # Set up DataFile as inheritable class data. Stuff->mk_classdata('DataFile'); # Declare the location of the data file for this class. Stuff->DataFile('/etc/stuff/data'); # Or, all in one shot: Stuff->mk_classdata(DataFile => '/etc/stuff/data'); =head1 DESCRIPTION Class::Data::Inheritable is for creating accessor/mutators to class data. That is, if you want to store something about your class as a whole (instead of about a single object). This data is then inherited by your subclasses and can be overriden. For example: Pere::Ubu->mk_classdata('Suitcase'); will generate the method Suitcase() in the class Pere::Ubu. This new method can be used to get and set a piece of class data. Pere::Ubu->Suitcase('Red'); $suitcase = Pere::Ubu->Suitcase; The interesting part happens when a class inherits from Pere::Ubu: package Raygun; use base qw(Pere::Ubu); # Raygun's suitcase is Red. $suitcase = Raygun->Suitcase; Raygun inherits its Suitcase class data from Pere::Ubu. Inheritance of class data works analogous to method inheritance. As long as Raygun does not "override" its inherited class data (by using Suitcase() to set a new value) it will continue to use whatever is set in Pere::Ubu and inherit further changes: # Both Raygun's and Pere::Ubu's suitcases are now Blue Pere::Ubu->Suitcase('Blue'); However, should Raygun decide to set its own Suitcase() it has now "overridden" Pere::Ubu and is on its own, just like if it had overriden a method: # Raygun has an orange suitcase, Pere::Ubu's is still Blue. Raygun->Suitcase('Orange'); Now that Raygun has overridden Pere::Ubu futher changes by Pere::Ubu no longer effect Raygun. # Raygun still has an orange suitcase, but Pere::Ubu is using Samsonite. Pere::Ubu->Suitcase('Samsonite'); =head1 Methods =head2 mk_classdata Class->mk_classdata($data_accessor_name); Class->mk_classdata($data_accessor_name => $value); This is a class method used to declare new class data accessors. A new accessor will be created in the Class using the name from $data_accessor_name, and optionally initially setting it to the given value. To facilitate overriding, mk_classdata creates an alias to the accessor, _field_accessor(). So Suitcase() would have an alias _Suitcase_accessor() that does the exact same thing as Suitcase(). This is useful if you want to alter the behavior of a single accessor yet still get the benefits of inheritable class data. For example. sub Suitcase { my($self) = shift; warn "Fashion tragedy" if @_ and $_[0] eq 'Plaid'; $self->_Suitcase_accessor(@_); } =head1 AUTHOR Original code by Damian Conway. Maintained by Michael G Schwern until September 2005. Now maintained by Tony Bowden. =head1 BUGS and QUERIES Please direct all correspondence regarding this module to: bug-Class-Data-Inheritable@rt.cpan.org =head1 COPYRIGHT and LICENSE Copyright (c) 2000-2005, Damian Conway and Michael G Schwern. All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself. =head1 SEE ALSO L has a very elaborate discussion of class data in Perl. PK iZac'0'0 Singleton.pmnu[#============================================================================ # # Class::Singleton.pm # # Implementation of a "singleton" module which ensures that a class has # only one instance and provides global access to it. For a description # of the Singleton class, see "Design Patterns", Gamma et al, Addison- # Wesley, 1995, ISBN 0-201-63361-2 # # Written by Andy Wardley # # Copyright (C) 1998-2008 Andy Wardley. All Rights Reserved. # Copyright (C) 1998 Canon Research Centre Europe Ltd. # #============================================================================ package Class::Singleton; require 5.004; use strict; use warnings; our $VERSION = 1.4; #======================================================================== # # instance() # # Module constructor. Creates an Class::Singleton (or derived) instance # if one doesn't already exist. The instance reference is stored in the # _instance variable of the $class package. This means that classes # derived from Class::Singleton will have the variables defined in *THEIR* # package, rather than the Class::Singleton package. The impact of this is # that you can create any number of classes derived from Class::Singleton # and create a single instance of each one. If the _instance variable # was stored in the Class::Singleton package, you could only instantiate # *ONE* object of *ANY* class derived from Class::Singleton. The first # time the instance is created, the _new_instance() constructor is called # which simply returns a reference to a blessed hash. This can be # overloaded for custom constructors. Any addtional parameters passed to # instance() are forwarded to _new_instance(). # # Returns a reference to the existing, or a newly created Class::Singleton # object. If the _new_instance() method returns an undefined value # then the constructer is deemed to have failed. # #======================================================================== sub instance { my $class = shift; # already got an object return $class if ref $class; # we store the instance in the _instance variable in the $class package. no strict 'refs'; my $instance = \${ "$class\::_instance" }; defined $$instance ? $$instance : ($$instance = $class->_new_instance(@_)); } #======================================================================= # has_instance() # # Public method to return the current instance if it exists. #======================================================================= sub has_instance { my $class = shift; $class = ref $class || $class; no strict 'refs'; return ${"$class\::_instance"}; } #======================================================================== # _new_instance(...) # # Simple constructor which returns a hash reference blessed into the # current class. May be overloaded to create non-hash objects or # handle any specific initialisation required. #======================================================================== sub _new_instance { my $class = shift; my %args = @_ && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_; bless { %args }, $class; } 1; __END__ =head1 NAME Class::Singleton - Implementation of a "Singleton" class =head1 SYNOPSIS use Class::Singleton; my $one = Class::Singleton->instance(); # returns a new instance my $two = Class::Singleton->instance(); # returns same instance =head1 DESCRIPTION This is the C module. A Singleton describes an object class that can have only one instance in any system. An example of a Singleton might be a print spooler or system registry. This module implements a Singleton class from which other classes can be derived. By itself, the C module does very little other than manage the instantiation of a single object. In deriving a class from C, your module will inherit the Singleton instantiation method and can implement whatever specific functionality is required. For a description and discussion of the Singleton class, see "Design Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2. =head1 PREREQUISITES C requires Perl version 5.004 or later. If you have an older version of Perl, please upgrade to latest version, available from your nearest CPAN site (see L below). =head1 INSTALLATION The C module is available from CPAN. As the 'perlmod' man page explains: CPAN stands for the Comprehensive Perl Archive Network. This is a globally replicated collection of all known Perl materials, including hundreds of unbunded modules. [...] For an up-to-date listing of CPAN sites, see http://www.perl.com/perl/ or ftp://ftp.perl.com/perl/ . The module is available in the following directories: /modules/by-module/Class/Class-Singleton-.tar.gz /authors/id/ABW/Class-Singleton-.tar.gz C is distributed as a single gzipped tar archive file: Class-Singleton-.tar.gz Note that "" represents the current version number, of the form "C<1.23>". See L below to determine the current version number for C. Unpack the archive to create an installation directory: gunzip Class-Singleton-.tar.gz tar xvf Class-Singleton-.tar 'cd' into that directory, make, test and install the module: cd Class-Singleton- perl Makefile.PL make make test make install The 'C' will install the module on your system. You may need root access to perform this task. If you install the module in a local directory (for example, by executing "C" in the above - see C for full details), you will need to ensure that the C environment variable is set to include the location, or add a line to your scripts explicitly naming the library location: use lib '/local/path/to/lib'; =head1 USING THE CLASS::SINGLETON MODULE To import and use the C module the following line should appear in your Perl program: use Class::Singleton; The L method is used to create a new C instance, or return a reference to an existing instance. Using this method, it is only possible to have a single instance of the class in any system. my $highlander = Class::Singleton->instance(); Assuming that no C object currently exists, this first call to L will create a new C and return a reference to it. Future invocations of L will return the same reference. my $macleod = Class::Singleton->instance(); In the above example, both C<$highlander> and C<$macleod> contain the same reference to a C instance. There can be only one. =head1 DERIVING SINGLETON CLASSES A module class may be derived from C and will inherit the L method that correctly instantiates only one object. package PrintSpooler; use base 'Class::Singleton'; # derived class specific code sub submit_job { ... } sub cancel_job { ... } The C class defined above could be used as follows: use PrintSpooler; my $spooler = PrintSpooler->instance(); $spooler->submit_job(...); The L method calls the L<_new_instance()> constructor method the first and only time a new instance is created. All parameters passed to the L method are forwarded to L<_new_instance()>. In the base class the L<_new_instance()> method returns a blessed reference to a hash array containing any arguments passed as either a hash reference or list of named parameters. 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 L<_new_instance()> method to provide more specific object initialisation or change the underlying object type (to a list reference, for example). 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 C L method uses a package variable to store a reference to any existing instance of the object. This variable, "C<_instance>", is coerced into the derived class package rather than the base class package. Thus, in the C example above, the instance variable would be: $MyApp::Database::_instance; This allows different classes to be derived from C that can co-exist in the same system, while still allowing only one instance of any one class to exists. For example, it would be possible to derive both 'C' and 'C' from C and have a single instance of I in a system, rather than a single instance of I. You can use the L method to find out if a particular class already has an instance defined. A reference to the instance is returned or C if none is currently defined. my $instance = MyApp::Database->has_instance() || warn "No instance is defined yet"; =head1 METHODS =head2 instance() This method is called to return a current object instance or create a new one by calling L<_new_instance()>. =head2 has_instance() This method returns a reference to any existing instance or C if none is defined. my $testing = MySingleton1->has_instance() || warn "No instance defined for MySingleton1"; =head2 _new_instance() This "private" method is called by L to create a new object instance if one doesn't already exist. It is not intended to be called directly (although there's nothing to stop 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 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 L method will I call the I<_new_instance()> method once, so any arguments you pass may be silently ignored if an instance already exists. You can use the L method to determine if an instance is already defined. =head1 AUTHOR Andy Wardley Eabw@wardley.orgE L Thanks to Andreas Koenig for providing some significant speedup patches and other ideas. =head1 VERSION This is version 1.4, released September 2007 =head1 COPYRIGHT Copyright Andy Wardley 1998-2007. All Rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut PK iZ3& Load/PP.pmnu[package Class::Load::PP; { $Class::Load::PP::VERSION = '0.20'; } use strict; use warnings; use Module::Runtime 'is_module_name'; use Package::Stash 0.14; use Scalar::Util 'blessed', 'reftype'; use Try::Tiny; sub is_class_loaded { my $class = shift; my $options = shift; my $loaded = _is_class_loaded($class); return $loaded if ! $loaded; return $loaded unless $options && $options->{-version}; return try { $class->VERSION($options->{-version}); 1; } catch { 0; }; } sub _is_class_loaded { my $class = shift; return 0 unless is_module_name($class); my $stash = Package::Stash->new($class); if ($stash->has_symbol('$VERSION')) { my $version = ${ $stash->get_symbol('$VERSION') }; if (defined $version) { return 1 if ! ref $version; # Sometimes $VERSION ends up as a reference to undef (weird) return 1 if ref $version && reftype $version eq 'SCALAR' && defined ${$version}; # a version object return 1 if blessed $version; } } if ($stash->has_symbol('@ISA')) { return 1 if @{ $stash->get_symbol('@ISA') }; } # check for any method return 1 if $stash->list_all_symbols('CODE'); # fail return 0; } 1; PKuiZz