home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / xampp / xampp-perl-addon-1.4.9-installer.exe / Accessor.pm < prev    next >
Encoding:
Perl POD Document  |  2004-03-09  |  16.3 KB  |  613 lines

  1. package Class::Accessor;
  2. require 5.00502;
  3. use strict;
  4. $Class::Accessor::VERSION = '0.19';
  5.  
  6. =head1 NAME
  7.  
  8.   Class::Accessor - Automated accessor generation
  9.  
  10. =head1 SYNOPSIS
  11.  
  12.   package Foo;
  13.  
  14.   use base qw(Class::Accessor);
  15.   Foo->mk_accessors(qw(this that whatever));
  16.  
  17.   # Meanwhile, in a nearby piece of code!
  18.   # Class::Accessor provides new().
  19.   my $foo = Foo->new;
  20.  
  21.   my $whatever = $foo->whatever;    # gets $foo->{whatever}
  22.   $foo->this('likmi');              # sets $foo->{this} = 'likmi'
  23.  
  24.   # Similar to @values = @{$foo}{qw(that whatever)}
  25.   @values = $foo->get(qw(that whatever));
  26.  
  27.   # sets $foo->{that} = 'crazy thing'
  28.   $foo->set('that', 'crazy thing');
  29.  
  30.  
  31. =head1 DESCRIPTION
  32.  
  33. This module automagically generates accessor/mutators for your class.
  34.  
  35. Most of the time, writing accessors is an exercise in cutting and
  36. pasting.  You usually wind up with a series of methods like this:
  37.  
  38.   # accessor for $obj->{foo}
  39.   sub foo {
  40.       my $self = shift;
  41.  
  42.       if(@_ == 1) {
  43.           $self->{foo} = shift;
  44.       }
  45.       elsif(@_ > 1) {
  46.           $self->{foo} = [@_];
  47.       }
  48.  
  49.       return $self->{foo};
  50.   }
  51.  
  52.  
  53.   # accessor for $obj->{bar}
  54.   sub bar {
  55.       my $self = shift;
  56.  
  57.       if(@_ == 1) {
  58.           $self->{bar} = shift;
  59.       }
  60.       elsif(@_ > 1) {
  61.           $self->{bar} = [@_];
  62.       }
  63.  
  64.       return $self->{bar};
  65.   }
  66.  
  67.   # etc...
  68.  
  69. One for each piece of data in your object.  While some will be unique,
  70. doing value checks and special storage tricks, most will simply be
  71. exercises in repetition.  Not only is it Bad Style to have a bunch of
  72. repetitious code, but its also simply not Lazy, which is the real
  73. tragedy.
  74.  
  75. If you make your module a subclass of Class::Accessor and declare your
  76. accessor fields with mk_accessors() then you'll find yourself with a
  77. set of automatically generated accessors which can even be
  78. customized!
  79.  
  80. The basic set up is very simple:
  81.  
  82.     package My::Class;
  83.     use base qw(Class::Accessor);
  84.     My::Class->mk_accessors( qw(foo bar car) );
  85.  
  86. Done.  My::Class now has simple foo(), bar() and car() accessors
  87. defined.
  88.  
  89. =head2 What Makes This Different?
  90.  
  91. What makes this module special compared to all the other method
  92. generating modules (L<"SEE ALSO">)?  By overriding the get() and set()
  93. methods you can alter the behavior of the accessors class-wide.  Also,
  94. the accessors are implemented as closures which should cost a bit less
  95. memory than most other solutions which generate a new method for each
  96. accessor.
  97.  
  98.  
  99. =head1 METHODS
  100.  
  101. =head2 new
  102.  
  103.     my $obj = Class->new;
  104.     my $obj = $other_obj->new;
  105.  
  106.     my $obj = Class->new(\%fields);
  107.     my $obj = $other_obj->new(\%fields);
  108.  
  109. Class::Accessor provides a basic constructor.  It generates a
  110. hash-based object and can be called as either a class method or an
  111. object method.
  112.  
  113. It takes an optional %fields hash which is used to initialize the
  114. object (handy if you use read-only accessors).  The fields of the hash
  115. correspond to the names of your accessors, so...
  116.  
  117.     package Foo;
  118.     use base qw(Class::Accessor);
  119.     Foo->mk_accessors('foo');
  120.  
  121.     my $obj = Class->new({ foo => 42 });
  122.     print $obj->foo;    # 42
  123.  
  124. however %fields can contain anything, new() will shove them all into
  125. your object.  Don't like it?  Override it.
  126.  
  127. =cut
  128.  
  129. sub new {
  130.     my($proto, $fields) = @_;
  131.     my($class) = ref $proto || $proto;
  132.  
  133.     $fields = {} unless defined $fields;
  134.  
  135.     # make a copy of $fields.
  136.     bless {%$fields}, $class;
  137. }
  138.  
  139. =head2 mk_accessors
  140.  
  141.     Class->mk_accessors(@fields);
  142.  
  143. This creates accessor/mutator methods for each named field given in
  144. @fields.  Foreach field in @fields it will generate two accessors.
  145. One called "field()" and the other called "_field_accessor()".  For
  146. example:
  147.  
  148.     # Generates foo(), _foo_accessor(), bar() and _bar_accessor().
  149.     Class->mk_accessors(qw(foo bar));
  150.  
  151. See L<CAVEATS AND TRICKS/"Overriding autogenerated accessors">
  152. for details.
  153.  
  154. =cut
  155.  
  156. sub mk_accessors {
  157.     my($self, @fields) = @_;
  158.  
  159.     $self->_mk_accessors('make_accessor', @fields);
  160. }
  161.  
  162.  
  163. {
  164.     no strict 'refs';
  165.  
  166.     sub _mk_accessors {
  167.         my($self, $maker, @fields) = @_;
  168.         my $class = ref $self || $self;
  169.  
  170.         # So we don't have to do lots of lookups inside the loop.
  171.         $maker = $self->can($maker) unless ref $maker;
  172.  
  173.         foreach my $field (@fields) {
  174.             if( $field eq 'DESTROY' ) {
  175.                 require Carp;
  176.                 &Carp::carp("Having a data accessor named DESTROY  in ".
  177.                              "'$class' is unwise.");
  178.             }
  179.  
  180.             my $accessor = $self->$maker($field);
  181.             my $alias = "_${field}_accessor";
  182.  
  183.             *{$class."\:\:$field"}  = $accessor
  184.               unless defined &{$class."\:\:$field"};
  185.  
  186.             *{$class."\:\:$alias"}  = $accessor
  187.               unless defined &{$class."\:\:$alias"};
  188.         }
  189.     }
  190. }
  191.  
  192. =head2 mk_ro_accessors
  193.  
  194.   Class->mk_ro_accessors(@read_only_fields);
  195.  
  196. Same as mk_accessors() except it will generate read-only accessors
  197. (ie. true accessors).  If you attempt to set a value with these
  198. accessors it will throw an exception.  It only uses get() and not
  199. set().
  200.  
  201.     package Foo;
  202.     use base qw(Class::Accessor);
  203.     Class->mk_ro_accessors(qw(foo bar));
  204.  
  205.     # Let's assume we have an object $foo of class Foo...
  206.     print $foo->foo;  # ok, prints whatever the value of $foo->{foo} is
  207.     $foo->foo(42);    # BOOM!  Naughty you.
  208.  
  209.  
  210. =cut
  211.  
  212. sub mk_ro_accessors {
  213.     my($self, @fields) = @_;
  214.  
  215.     $self->_mk_accessors('make_ro_accessor', @fields);
  216. }
  217.  
  218. =head2 mk_wo_accessors
  219.  
  220.   Class->mk_wo_accessors(@write_only_fields);
  221.  
  222. Same as mk_accessors() except it will generate write-only accessors
  223. (ie. mutators).  If you attempt to read a value with these accessors
  224. it will throw an exception.  It only uses set() and not get().
  225.  
  226. B<NOTE> I'm not entirely sure why this is useful, but I'm sure someone
  227. will need it.  If you've found a use, let me know.  Right now its here
  228. for orthoginality and because its easy to implement.
  229.  
  230.     package Foo;
  231.     use base qw(Class::Accessor);
  232.     Class->mk_wo_accessors(qw(foo bar));
  233.  
  234.     # Let's assume we have an object $foo of class Foo...
  235.     $foo->foo(42);      # OK.  Sets $self->{foo} = 42
  236.     print $foo->foo;    # BOOM!  Can't read from this accessor.
  237.  
  238. =cut
  239.  
  240. sub mk_wo_accessors {
  241.     my($self, @fields) = @_;
  242.  
  243.     $self->_mk_accessors('make_wo_accessor', @fields);
  244. }
  245.  
  246. =head1 DETAILS
  247.  
  248. An accessor generated by Class::Accessor looks something like
  249. this:
  250.  
  251.     # Your foo may vary.
  252.     sub foo {
  253.         my($self) = shift;
  254.         if(@_) {    # set
  255.             return $self->set('foo', @_);
  256.         }
  257.         else {
  258.             return $self->get('foo');
  259.         }
  260.     }
  261.  
  262. Very simple.  All it does is determine if you're wanting to set a
  263. value or get a value and calls the appropriate method.
  264. Class::Accessor provides default get() and set() methods which
  265. your class can override.  They're detailed later.
  266.  
  267. =head2 Modifying the behavior of the accessor
  268.  
  269. Rather than actually modifying the accessor itself, it is much more
  270. sensible to simply override the two key methods which the accessor
  271. calls.  Namely set() and get().
  272.  
  273. If you -really- want to, you can override make_accessor().
  274.  
  275. =head2 set
  276.  
  277.     $obj->set($key, $value);
  278.     $obj->set($key, @values);
  279.  
  280. set() defines how generally one stores data in the object.
  281.  
  282. override this method to change how data is stored by your accessors.
  283.  
  284. =cut
  285.  
  286. sub set {
  287.     my($self, $key) = splice(@_, 0, 2);
  288.  
  289.     if(@_ == 1) {
  290.         $self->{$key} = $_[0];
  291.     }
  292.     elsif(@_ > 1) {
  293.         $self->{$key} = [@_];
  294.     }
  295.     else {
  296.         require Carp;
  297.         &Carp::confess("Wrong number of arguments received");
  298.     }
  299. }
  300.  
  301. =head2 get
  302.  
  303.     $value  = $obj->get($key);
  304.     @values = $obj->get(@keys);
  305.  
  306. get() defines how data is retreived from your objects.
  307.  
  308. override this method to change how it is retreived.
  309.  
  310. =cut
  311.  
  312. sub get {
  313.     my $self = shift;
  314.  
  315.     if(@_ == 1) {
  316.         return $self->{$_[0]};
  317.     }
  318.     elsif( @_ > 1 ) {
  319.         return @{$self}{@_};
  320.     }
  321.     else {
  322.         require Carp;
  323.         &Carp::confess("Wrong number of arguments received.");
  324.     }
  325. }
  326.  
  327. =head2 make_accessor
  328.  
  329.     $accessor = Class->make_accessor($field);
  330.  
  331. Generates a subroutine reference which acts as an accessor for the given
  332. $field.  It calls get() and set().
  333.  
  334. If you wish to change the behavior of your accessors, try overriding
  335. get() and set() before you start mucking with make_accessor().
  336.  
  337. =cut
  338.  
  339. sub make_accessor {
  340.     my ($class, $field) = @_;
  341.  
  342.     # Build a closure around $field.
  343.     return sub {
  344.         my $self = shift;
  345.  
  346.         if(@_) {
  347.             return $self->set($field, @_);
  348.         }
  349.         else {
  350.             return $self->get($field);
  351.         }
  352.     };
  353. }
  354.  
  355. =head2 make_ro_accessor
  356.  
  357.     $read_only_accessor = Class->make_ro_accessor($field);
  358.  
  359. Generates a subroutine refrence which acts as a read-only accessor for
  360. the given $field.  It only calls get().
  361.  
  362. Override get() to change the behavior of your accessors.
  363.  
  364. =cut
  365.  
  366. sub make_ro_accessor {
  367.     my($class, $field) = @_;
  368.  
  369.     return sub {
  370.         my $self = shift;
  371.  
  372.         if(@_) {
  373.             my $caller = caller;
  374.             require Carp;
  375.             Carp::croak("'$caller' cannot alter the value of '$field' on ".
  376.                         "objects of class '$class'");
  377.         }
  378.         else {
  379.             return $self->get($field);
  380.         }
  381.     };
  382. }
  383.  
  384. =head2 make_wo_accessor
  385.  
  386.     $read_only_accessor = Class->make_wo_accessor($field);
  387.  
  388. Generates a subroutine refrence which acts as a write-only accessor
  389. (mutator) for the given $field.  It only calls set().
  390.  
  391. Override set() to change the behavior of your accessors.
  392.  
  393. =cut
  394.  
  395. sub make_wo_accessor {
  396.     my($class, $field) = @_;
  397.  
  398.     return sub {
  399.         my $self = shift;
  400.  
  401.         unless (@_) {
  402.             my $caller = caller;
  403.             require Carp;
  404.             Carp::croak("'$caller' cannot access the value of '$field' on ".
  405.                         "objects of class '$class'");
  406.         }
  407.         else {
  408.             return $self->set($field, @_);
  409.         }
  410.     };
  411. }
  412.  
  413. =head1 EFFICIENCY
  414.  
  415. Class::Accessor does not employ an autoloader, thus it is much faster
  416. than you'd think.  Its generated methods incur no special penalty over
  417. ones you'd write yourself.
  418.  
  419. Here are Schwern's results of benchmarking Class::Accessor,
  420. Class::Accessor::Fast, a hand-written accessor, and direct hash access.
  421.  
  422.   Benchmark: timing 500000 iterations of By Hand - get, By Hand - set,
  423.     C::A - get, C::A - set, C::A::Fast - get, C::A::Fast - set,
  424.     Direct - get, Direct - set...
  425.  
  426.   By Hand - get:  4 wallclock secs ( 5.09 usr +  0.00 sys =  5.09 CPU)
  427.                   @ 98231.83/s (n=500000)
  428.   By Hand - set:  5 wallclock secs ( 6.06 usr +  0.00 sys =  6.06 CPU)
  429.                   @ 82508.25/s (n=500000)
  430.   C::A - get:  9 wallclock secs ( 9.83 usr +  0.01 sys =  9.84 CPU)
  431.                @ 50813.01/s (n=500000)
  432.   C::A - set: 11 wallclock secs ( 9.95 usr +  0.00 sys =  9.95 CPU)
  433.                @ 50251.26/s (n=500000)
  434.   C::A::Fast - get:  6 wallclock secs ( 4.88 usr +  0.00 sys =  4.88 CPU)
  435.                      @ 102459.02/s (n=500000)
  436.   C::A::Fast - set:  6 wallclock secs ( 5.83 usr +  0.00 sys =  5.83 CPU)
  437.                      @ 85763.29/s (n=500000)
  438.   Direct - get:  0 wallclock secs ( 0.89 usr +  0.00 sys =  0.89 CPU)
  439.                  @ 561797.75/s (n=500000)
  440.   Direct - set:  2 wallclock secs ( 0.87 usr +  0.00 sys =  0.87 CPU)
  441.                  @ 574712.64/s (n=500000)
  442.  
  443. So Class::Accessor::Fast is just as fast as one you'd write yourself
  444. while Class::Accessor is twice as slow, a price paid for flexibility.
  445. Direct hash access is about six times faster, but provides no
  446. encapsulation and no flexibility.
  447.  
  448. Of course, its not as simple as saying "Class::Accessor is twice as
  449. slow as one you write yourself".  These are benchmarks for the
  450. simplest possible accessor, if your accessors do any sort of
  451. complicated work (such as talking to a database or writing to a file)
  452. the time spent doing that work will quickly swamp the time spend just
  453. calling the accessor.  In that case, Class::Accessor and the ones you
  454. write will tend to be just as fast.
  455.  
  456.  
  457. =head1 EXAMPLES
  458.  
  459. Here's an example of generating an accessor for every public field of
  460. your class.
  461.  
  462.     package Altoids;
  463.  
  464.     use base qw(Class::Accessor Class::Fields);
  465.     use fields qw(curiously strong mints);
  466.     Altoids->mk_accessors( Altoids->show_fields('Public') );
  467.  
  468.     sub new {
  469.         my $proto = shift;
  470.         my $class = ref $proto || $proto;
  471.         return fields::new($class);
  472.     }
  473.  
  474.     my Altoids $tin = Altoids->new;
  475.  
  476.     $tin->curiously('Curiouser and curiouser');
  477.     print $tin->{curiously};    # prints 'Curiouser and curiouser'
  478.  
  479.  
  480.     # Subclassing works, too.
  481.     package Mint::Snuff;
  482.     use base qw(Altoids);
  483.  
  484.     my Mint::Snuff $pouch = Mint::Snuff->new;
  485.     $pouch->strong('Fuck you up strong!');
  486.     print $pouch->{strong};     # prints 'Fuck you up strong!'
  487.  
  488.  
  489. Here's a simple example of altering the behavior of your accessors.
  490.  
  491.     package Foo;
  492.     use base qw(Class::Accessor);
  493.     Foo->mk_accessor(qw(this that up down));
  494.  
  495.     sub get {
  496.         my $self = shift;
  497.  
  498.         # Note every time someone gets some data.
  499.         print STDERR "Getting @_\n";
  500.  
  501.         $self->SUPER::get(@_);
  502.     }
  503.  
  504.     sub set {
  505.         my ($self, $key) = splice(@_, 0, 2);
  506.  
  507.         # Note every time someone sets some data.
  508.         print STDERR "Setting $key to @_\n";
  509.  
  510.         $self->SUPER::set($key, @_);
  511.     }
  512.  
  513.  
  514. =head1 CAVEATS AND TRICKS
  515.  
  516. Class::Accessor has to do some internal wackiness to get its
  517. job done quickly and efficiently.  Because of this, there's a few
  518. tricks and traps one must know about.
  519.  
  520. Hey, nothing's perfect.
  521.  
  522. =head2 Don't make a field called DESTROY
  523.  
  524. This is bad.  Since DESTROY is a magical method it would be bad for us
  525. to define an accessor using that name.  Class::Accessor will
  526. carp if you try to use it with a field named "DESTROY".
  527.  
  528. =head2 Overriding autogenerated accessors
  529.  
  530. You may want to override the autogenerated accessor with your own, yet
  531. have your custom accessor call the default one.  For instance, maybe
  532. you want to have an accessor which checks its input.  Normally, one
  533. would expect this to work:
  534.  
  535.     package Foo;
  536.     use base qw(Class::Accessor);
  537.     Foo->mk_accessors(qw(email this that whatever));
  538.  
  539.     # Only accept addresses which look valid.
  540.     sub email {
  541.         my($self) = shift;
  542.         my($email) = @_;
  543.  
  544.         if( @_ ) {  # Setting
  545.             require Email::Valid;
  546.             unless( Email::Valid->address($email) ) {
  547.                 carp("$email doesn't look like a valid address.");
  548.                 return;
  549.             }
  550.         }
  551.  
  552.         return $self->SUPER::email(@_);
  553.     }
  554.  
  555. There's a subtle problem in the last example, and its in this line:
  556.  
  557.     return $self->SUPER::email(@_);
  558.  
  559. If we look at how Foo was defined, it called mk_accessors() which
  560. stuck email() right into Foo's namespace.  There *is* no
  561. SUPER::email() to delegate to!  Two ways around this... first is to
  562. make a "pure" base class for Foo.  This pure class will generate the
  563. accessors and provide the necessary super class for Foo to use:
  564.  
  565.     package Pure::Organic::Foo;
  566.     use base qw(Class::Accessor);
  567.     Pure::Organic::Foo->mk_accessors(qw(email this that whatever));
  568.  
  569.     package Foo;
  570.     use base qw(Pure::Organic::Foo);
  571.  
  572. And now Foo::email() can override the generated
  573. Pure::Organic::Foo::email() and use it as SUPER::email().
  574.  
  575. This is probably the most obvious solution to everyone but me.
  576. Instead, what first made sense to me was for mk_accessors() to define
  577. an alias of email(), _email_accessor().  Using this solution,
  578. Foo::email() would be written with:
  579.  
  580.     return $self->_email_accessor(@_);
  581.  
  582. instead of the expected SUPER::email().
  583.  
  584.  
  585. =head1 CURRENT AUTHOR
  586.  
  587. Marty Pauley <marty+perl@kasei.com>
  588.  
  589. =head1 ORIGINAL AUTHOR
  590.  
  591. Michael G Schwern <schwern@pobox.com>
  592.  
  593. =head1 THANKS
  594.  
  595. Liz, for performance tweaks.
  596.  
  597. Tels, for his big feature request/bug report.
  598.  
  599.  
  600. =head1 SEE ALSO
  601.  
  602. L<Class::Accessor::Fast>
  603.  
  604. These are some modules which do similar things in different ways
  605. L<Class::Struct>, L<Class::Methodmaker>, L<Class::Generate>,
  606. L<Class::Class>, L<Class::Contract>
  607.  
  608. L<Class::DBI> for an example of this module in use.
  609.  
  610. =cut
  611.  
  612. 1;
  613.