accessor.pm
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· PM 代码 · 共 751 行 · 第 1/2 页
PM
751 行
package Object::Accessor;use strict;use Carp qw[carp croak];use vars qw[$FATAL $DEBUG $AUTOLOAD $VERSION];use Params::Check qw[allow];use Data::Dumper;### some objects might have overload enabled, we'll need to### disable string overloading for callbacksrequire overload;$VERSION = '0.32';$FATAL = 0;$DEBUG = 0;use constant VALUE => 0; # array index in the hash valueuse constant ALLOW => 1; # array index in the hash value=head1 NAMEObject::Accessor=head1 SYNOPSIS ### using the object $obj = Object::Accessor->new; # create object $obj = Object::Accessor->new(@list); # create object with accessors $obj = Object::Accessor->new(\%h); # create object with accessors # and their allow handlers $bool = $obj->mk_accessors('foo'); # create accessors $bool = $obj->mk_accessors( # create accessors with input {foo => ALLOW_HANDLER} ); # validation $clone = $obj->mk_clone; # create a clone of original # object without data $bool = $obj->mk_flush; # clean out all data @list = $obj->ls_accessors; # retrieves a list of all # accessors for this object $bar = $obj->foo('bar'); # set 'foo' to 'bar' $bar = $obj->foo(); # retrieve 'bar' again $sub = $obj->can('foo'); # retrieve coderef for # 'foo' accessor $bar = $sub->('bar'); # set 'foo' via coderef $bar = $sub->(); # retrieve 'bar' by coderef ### using the object as base class package My::Class; use base 'Object::Accessor'; $obj = My::Class->new; # create base object $bool = $obj->mk_accessors('foo'); # create accessors, etc... ### make all attempted access to non-existant accessors fatal ### (defaults to false) $Object::Accessor::FATAL = 1; ### enable debugging $Object::Accessor::DEBUG = 1; ### advanced usage -- callbacks { my $obj = Object::Accessor->new('foo'); $obj->register_callback( sub { ... } ); $obj->foo( 1 ); # these calls invoke the callback you registered $obj->foo() # which allows you to change the get/set # behaviour and what is returned to the caller. } ### advanced usage -- lvalue attributes { my $obj = Object::Accessor::Lvalue->new('foo'); print $obj->foo = 1; # will print 1 } ### advanced usage -- scoped attribute values { my $obj = Object::Accessor->new('foo'); $obj->foo( 1 ); print $obj->foo; # will print 1 ### bind the scope of the value of attribute 'foo' ### to the scope of '$x' -- when $x goes out of ### scope, 'foo's previous value will be restored { $obj->foo( 2 => \my $x ); print $obj->foo, ' ', $x; # will print '2 2' } print $obj->foo; # will print 1 }=head1 DESCRIPTIONC<Object::Accessor> provides an interface to create per objectaccessors (as opposed to per C<Class> accessors, as, for example,C<Class::Accessor> provides).You can choose to either subclass this module, and thus using itsaccessors on your own module, or to store an C<Object::Accessor>object inside your own object, and access the accessors from there.See the C<SYNOPSIS> for examples.=head1 METHODS=head2 $object = Object::Accessor->new( [ARGS] );Creates a new (and empty) C<Object::Accessor> object. This method isinheritable.Any arguments given to C<new> are passed straight to C<mk_accessors>.If you want to be able to assign to your accessors as if theywere C<lvalue>s, you should create your object in the C<Object::Acccessor::Lvalue> namespace instead. See the sectionon C<LVALUE ACCESSORS> below.=cutsub new { my $class = shift; my $obj = bless {}, $class; $obj->mk_accessors( @_ ) if @_; return $obj;}=head2 $bool = $object->mk_accessors( @ACCESSORS | \%ACCESSOR_MAP );Creates a list of accessors for this object (and C<NOT> for other onesin the same class!).Will not clobber existing data, so if an accessor already exists,requesting to create again is effectively a C<no-op>.When providing a C<hashref> as argument, rather than a normal list,you can specify a list of key/value pairs of accessors and theirrespective input validators. The validators can be anything thatC<Params::Check>'s C<allow> function accepts. Please see its manpagefor details.For example: $object->mk_accessors( { foo => qr/^\d+$/, # digits only bar => [0,1], # booleans zot => \&my_sub # a custom verification sub } ); Returns true on success, false on failure.Accessors that are called on an object, that do not exist returnC<undef> by default, but you can make this a fatal error by setting theglobal variable C<$FATAL> to true. See the section on C<GLOBALVARIABLES> for details.Note that you can bind the values of attributes to a scope. This allowsyou to C<temporarily> change a value of an attribute, and have it's original value restored up on the end of it's bound variable's scope;For example, in this snippet of code, the attribute C<foo> will temporarily be set to C<2>, until the end of the scope of C<$x>, at which point the original value of C<1> will be restored. my $obj = Object::Accessor->new; $obj->mk_accessors('foo'); $obj->foo( 1 ); print $obj->foo; # will print 1 ### bind the scope of the value of attribute 'foo' ### to the scope of '$x' -- when $x goes out of ### scope, 'foo' previous value will be restored { $obj->foo( 2 => \my $x ); print $obj->foo, ' ', $x; # will print '2 2' } print $obj->foo; # will print 1 Note that all accessors are read/write for everyone. See the C<TODO>section for details.=cutsub mk_accessors { my $self = $_[0]; my $is_hash = UNIVERSAL::isa( $_[1], 'HASH' ); ### first argument is a hashref, which means key/val pairs ### as keys + allow handlers for my $acc ( $is_hash ? keys %{$_[1]} : @_[1..$#_] ) { ### already created apparently if( exists $self->{$acc} ) { __PACKAGE__->___debug( "Accessor '$acc' already exists"); next; } __PACKAGE__->___debug( "Creating accessor '$acc'"); ### explicitly vivify it, so that exists works in ls_accessors() $self->{$acc}->[VALUE] = undef; ### set the allow handler only if one was specified $self->{$acc}->[ALLOW] = $_[1]->{$acc} if $is_hash; } return 1;}=head2 @list = $self->ls_accessors;Returns a list of accessors that are supported by the current object.The corresponding coderefs can be retrieved by passing this list oneby one to the C<can> method.=cutsub ls_accessors { ### metainformation is stored in the stringified ### key of the object, so skip that when listing accessors return sort grep { $_ ne "$_[0]" } keys %{$_[0]};}=head2 $ref = $self->ls_allow(KEY)Returns the allow handler for the given key, which can be used withC<Params::Check>'s C<allow()> handler. If there was no allow handlerspecified, an allow handler that always returns true will be returned.=cutsub ls_allow { my $self = shift; my $key = shift or return; return exists $self->{$key}->[ALLOW] ? $self->{$key}->[ALLOW] : sub { 1 };}=head2 $clone = $self->mk_clone;Makes a clone of the current object, which will have the exact sameaccessors as the current object, but without the data stored in them.=cut### XXX this creates an object WITH allow handlers at all times.### even if the original didntsub mk_clone { my $self = $_[0]; my $class = ref $self; my $clone = $class->new; ### split out accessors with and without allow handlers, so we ### don't install dummy allow handers (which makes O::A::lvalue ### warn for exampel) my %hash; my @list; for my $acc ( $self->ls_accessors ) { my $allow = $self->{$acc}->[ALLOW]; $allow ? $hash{$acc} = $allow : push @list, $acc; } ### copy the accessors from $self to $clone $clone->mk_accessors( \%hash ) if %hash; $clone->mk_accessors( @list ) if @list; ### copy callbacks #$clone->{"$clone"} = $self->{"$self"} if $self->{"$self"}; $clone->___callback( $self->___callback ); return $clone;}=head2 $bool = $self->mk_flush;Flushes all the data from the current object; all accessors will beset back to their default state of C<undef>.Returns true on success and false on failure.=cutsub mk_flush { my $self = $_[0]; # set each accessor's data to undef $self->{$_}->[VALUE] = undef for $self->ls_accessors; return 1;}=head2 $bool = $self->mk_verify;Checks if all values in the current object are in accordance with theirown allow handler. Specifically useful to check if an empty initialisedobject has been filled with values satisfying their own allow criteria.=cutsub mk_verify { my $self = $_[0]; my $fail; for my $name ( $self->ls_accessors ) { unless( allow( $self->$name, $self->ls_allow( $name ) ) ) { my $val = defined $self->$name ? $self->$name : '<undef>'; __PACKAGE__->___error("'$name' ($val) is invalid"); $fail++; } } return if $fail; return 1;} =head2 $bool = $self->register_callback( sub { ... } );This method allows you to register a callback, that is invokedevery time an accessor is called. This allows you to munge inputdata, access external data stores, etc.You are free to return whatever you wish. On a C<set> call, thedata is even stored in the object.Below is an example of the use of a callback. $object->some_method( "some_value" ); my $callback = sub { my $self = shift; # the object my $meth = shift; # "some_method" my $val = shift; # ["some_value"] # could be undef -- check 'exists'; # if scalar @$val is empty, it was a 'get' # your code here return $new_val; # the value you want to be set/returned } To access the values stored in the object, circumventing thecallback structure, you should use the C<___get> and C<___set> methodsdocumented further down. =cutsub register_callback { my $self = shift; my $sub = shift or return; ### use the memory address as key, it's not used EVER as an ### accessor --kane $self->___callback( $sub ); return 1;}=head2 $bool = $self->can( METHOD_NAME )This method overrides C<UNIVERAL::can> in order to provide coderefs toaccessors which are loaded on demand. It will behave just likeC<UNIVERSAL::can> where it can -- returning a class method if it exists,or a closure pointing to a valid accessor of this particular object.You can use it as follows: $sub = $object->can('some_accessor'); # retrieve the coderef $sub->('foo'); # 'some_accessor' now set # to 'foo' for $object $foo = $sub->(); # retrieve the contents
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?