[Templates-cvs] cvs commit: TT3/lib/Template Base.pm

cvs@template-toolkit.org cvs@template-toolkit.org
Mon, 13 Dec 2004 12:27:10 +0000


cvs         04/12/13 12:27:09

  Modified:    lib/Template Base.pm
  Log:
  * various documentation updates, cleanups, etc.
  
  Revision  Changes    Path
  1.16      +181 -174  TT3/lib/Template/Base.pm
  
  Index: Base.pm
  ===================================================================
  RCS file: /template-toolkit/TT3/lib/Template/Base.pm,v
  retrieving revision 1.15
  retrieving revision 1.16
  diff -u -r1.15 -r1.16
  --- Base.pm	2004/12/12 15:50:00	1.15
  +++ Base.pm	2004/12/13 12:27:09	1.16
  @@ -16,7 +16,7 @@
   #   modify it under the same terms as Perl itself.
   #
   # REVISION
  -#   $Id: Base.pm,v 1.15 2004/12/12 15:50:00 abw Exp $
  +#   $Id: Base.pm,v 1.16 2004/12/13 12:27:09 abw Exp $
   #
   #========================================================================
   
  @@ -29,13 +29,13 @@
   require Template::Utils;
   require Template::Exception;
   
  -our $VERSION   = sprintf("%d.%02d", q$Revision: 1.15 $ =~ /(\d+)\.(\d+)/);
  +our $VERSION   = sprintf("%d.%02d", q$Revision: 1.16 $ =~ /(\d+)\.(\d+)/);
   our $DEBUG     = 0 unless defined $DEBUG;
   our $ERROR     = '';
   our $PAD       = '  ';
   our $TEXTLEN   = 32;
   our $UTILS     = 'Template::Utils';
  -our $EXCEPTION = 'Template::Exception';
  +our $EXCEPTION = 'Template::Exception' unless defined $EXCEPTION;
   
   
   #------------------------------------------------------------------------
  @@ -318,9 +318,7 @@
   # throw($type, $error)
   # throw($type, $error, @args)
   #
  -# This method throws an exception by calling die().  It can be called with
  -# one passed an
  -# exception object, or an error message which will be upgraded to 
  +# This method throws an exception by calling die(). 
   #------------------------------------------------------------------------
   
   sub throw {
  @@ -466,87 +464,6 @@
   
   
   #------------------------------------------------------------------------
  -# module($name, $config)
  -#
  -# Load a module.  The $name passed should correspond to an object item 
  -# indicating the module package name 
  -# (e.g. scanner => Template::Scanner)
  -#------------------------------------------------------------------------
  -
  -# TODO: this should be deprecated and/or moved into Template::Utils
  -
  -sub module {
  -    my $self = shift;
  -
  -    my ($pkg, $file, $line) = caller(0);
  -    die "module() has been deprecated, please fix the code at $file line $line\n";
  -
  -    my $name = shift;
  -    my $config = @_ && UNIVERSAL::isa($_[0], 'HASH') ? shift : { @_ };
  -
  -    $self->debug("module($name)\n") if $self->{ DEBUG };
  -
  -    # TODO: may want to implement caching, e.g. have an object
  -    # cache => { scanner => 1, parser => 1, handler => 0 } item
  -    # and then cache objects accordingly
  -
  -    # $config or $self should define a $name item (e.g. 'scanner', 
  -    # 'parser', etc, to provide an object or class name
  -    my $package = $config->{ $name } || $self->{ $name }
  -        || return $self->error("no $name module defined");
  -
  -    # item may already be an object
  -    return $package if ref $package;
  -
  -    # $config or $self can have set a load_$item flag (e.g. 'load_scanner',
  -    # 'load_parser') to enable/disable loading of that module
  -    my $load_key = "load_$name";
  -
  -    if (exists $config->{ $load_key } 
  -             ? $config->{ $load_key }
  -             : exists $self->{ $load_key } 
  -                    ? $self->{ $load_key }
  -                    : 1 ) {
  -
  -        # load module
  -        $UTILS->load_module($package) 
  -            || return $self->error($UTILS->error());
  -
  -        # don't bother loading it again
  -        $self->{ $load_key } = 0;
  -    }
  -
  -    return $package;
  -}
  -
  -
  -# TODO: this should be deprecated and/or moved into Template::Utils
  -
  -#------------------------------------------------------------------------
  -# object($name, $config)
  -#
  -# Load a module and instantiate an object.
  -#------------------------------------------------------------------------
  -
  -sub object {
  -    my $self = shift;
  -    my $name = shift;
  -
  -    my ($pkg, $file, $line) = caller(0);
  -    die "object() has been deprecated, please fix the code at $file line $line\n";
  -
  -    my $module = $self->module( $name ) || return;
  -
  -    # module may already be an object
  -    return $module if ref $module;
  -
  -    # otherwise create one
  -    return $module->new(@_)
  -        || $self->error("failed to create $name: ", $module->error());
  -}
  -
  -
  -#------------------------------------------------------------------------
   # version()
   #
   # Return the value of the $VERSION package variable for the object.
  @@ -698,37 +615,39 @@
       use Template::Base;
       use base qw( Template::Base );
   
  +    our $ERROR = '';    
  +    our $DEBUG = 0 unless defined $DEBUG;
  +    
       # define init() method for initialisation
  -
  +    
       sub init {
           my ($self, $config) 
           
           # $config is a hash of named parameters
           $self->{ name } = $config->{ name } 
               || return $self->error('no name specified');
  -
  +    
           # return $self to indicate success
           return $self;
       }
  -
  +    
       # rest of the module follows...
  -
  +    
       package main;
  -
  +    
       # using the module
  -
  +    
       my $object = My::Template::Module->new( name => 'thingy' )
           || die My::Template::Module->error();
   
   =head1 DESCRIPTION
   
  -TODO: decline() and decline() have changed a litte from what is documented.
  +This module implements a base class object from which most (if not
  +all) of the other Template Toolkit modules are derived.  It implements
  +a number of methods to aid in object creation and configuration, error
  +reporting, debugging, and for loading and instantiating objects of
  +other classes.
   
  -This module implements a base class object from which most of the
  -other Template Toolkit modules are derived.  It implements a number of
  -methods to aid in object creation and configuration, error reporting,
  -debugging, and for loading and instantiating objects of other classes.
  -
   =head1 METHODS
   
   =head2 new(\%config)
  @@ -744,7 +663,7 @@
           arg2 => 'value2',
           ...etc...
       });
  -
  +    
       # list of named params
       my $object = My::Template::Module->new(
           arg1 => 'value1',
  @@ -772,10 +691,52 @@
       my $object = My::Template::Module->new()
           || die $My::Template::Module::ERROR;
   
  +=head3 Configuration Options
  +
  +The following configuration options are provided by default for 
  +all objects derived from the Template::Base module that inherit
  +its C<new()> method.
  +
  +=head4 debug
  +
  +A flag to enable debugging for this object.  Sets an internal
  +C<DEBUG> flag to the value provided, or uses the default value
  +set in the C<$DEBUG> package variable.
  +
  +    my $object = My::Template::Module->new( debug => 1 );
  +
  +    # alternately, set $DEBUG package variable
  +    $My::Template::Module::DEBUG = 1;
  +
  +    # debugging now enabled by default
  +    my $object = My::Template::Module->new();
  +
  +    # explicitly disable debugging on a per-object basis
  +    my $object = My::Template::Module->new( debug => 0 );
  +
  +=head4 throw
  +
  +This option can be set to cause the object to throw as exceptions any
  +and all errors raised by calls to the C<error($msg)> method.  A
  +Template::Exception object is created (or an object of whatever class
  +is defined in the C<$EXCEPTION> package variable) with its C<type>
  +set to the value of the C<throw> parameter and C<info> field containing
  +the error message passed to the C<error($msg)> method.
  +
  +    my $object = My::Template::Module->new( throw => 'wibble' );
  +
  +    $object->error('wibble is wobbling');
  +
  +In the preceding example, the call to the C<error()> method 
  +results in an exception object being throw via die with a C<type>
  +of 'wibble' and <info> set to 'wibble is wobbling'.
  +
  +See the C<error()> and C<throw()> methods for further details.
  +
   =head2 clone(\%config)
   
   This method creates a copy of the current object and then calls its
  -init() method, forwarding to it any arguments passed.
  +C<init()> method, forwarding to it any arguments passed.
   
       my $copy = $object->clone( answer => '69, dude!' )
           || die $object->error();
  @@ -789,7 +750,7 @@
   
       sub init {
           my ($self, $config) = @_;
  -
  +    
           # set the 'answer' parameter or default to 42
           $self->{ answer } = $config->{ answer } || 42;
           
  @@ -810,16 +771,15 @@
   
       sub init {
           my ($self, $config) = @_;
  -
  +    
           # set the 'answer' parameter or report error
           $self->{ answer } = $config->{ answer }
               || return $self->error('no answer supplied');
           
           return $self;
       }
  -
   
  -=head2 pkgvar($name, $default)
  +=head2 pkgvar($name, $default, $all)
   
   This method provides a convenient way to examine for the value of a
   scalar package variable.  The first argument, C<$name>, provides the
  @@ -829,14 +789,33 @@
   
       sub init {
           my ($self, $config) = @_;
  -
  +    
           # allow $LIMIT to be specified as a package 
           # variable or default to a value of 10
           $self->{ limit } = $self->pkgvar( LIMIT => 10 );
  -
  +    
           return $self;
       }
   
  +The third argument is a flag which can be set to any true value to 
  +have the method return a list of all instances of the variable in 
  +the object's class and all of its parents' classes.  This implements
  +the functionality for pkgvars().
  +
  +=head2 pkgvars($name, $default)
  +
  +This method is a wrapper around pkgvar() which sets the C<$all> flag
  +true to return a list of all instances of the named variable.  The
  +error_msg() method uses this, for example, to look for an error
  +message defined in a hash reference in any of its or its parents'
  +C<$ERRORS> package variables.
  +
  +    foreach my $errors ($self->pkgvars('ERRORS')) {
  +        if (my $format = $errors->{ $code }) {
  +            return $self->error(sprintf($format, @args));
  +        }
  +    }
  +
   =head2 pkgconf(\%config, @params)
   
   This method looks in the hash array referenced by the first argument
  @@ -844,66 +823,33 @@
   
       sub init {
           my ($self, $config) = @_;
  -
  +    
           $self->pkgconf($config, qw( size limit )) 
               || return;
  -
  +    
           return $self;
       }
   
  -It first looks for the parameter as specified (e.g. 'size').  If not
  -defined it then looks for the upper case equivalent (e.g. 'SIZE').
  -Failing that it then looks for a package variable (e.g. '$SIZE') in
  +It first looks for the parameter as specified (e.g. <size>).  If not
  +defined it then looks for the upper case equivalent (e.g. C<SIZE>).
  +Failing that it then looks for a package variable (e.g. C<$SIZE>) in
   the subclass package and then in the caller's package.  If any of
   these searches return a defined value then it is copied into C<$self>
   using the original name (i.e. 'size') as a key.  Otherwise the method
   returns an error.
  -
  -=head2 module($name, \%config)
  -
  -This method looks in the current object for the name of a module defined
  -by the first argument and loads it.
  -
  -    my $object = My::Template::Module->new({
  -        warp_drive => 'My::Warp::Drive'
  -    });
   
  -    my $warpmod = $object->module('warp_drive');
  +Note that this method is provided in the short-term to ease the
  +process of backward compatability with TT2.  It may be deprecated in
  +the future (or modified to use pkgvar()) and the current behaviour
  +should not be relied upon as it may change.
   
  -The object can also set an internal flag of the form "load_$name" to override
  -the default behaviour of loading the relevant module.
  -
  -    my $object = My::Template::Module->new({
  -        warp_drive => 'My::Warp::Drive'
  -        load_warp_drive => 0,
  -    });
  -
  -A list of named arguments, or a reference to a hash array of the same, can 
  -follow the module name, providing custom values for these items.
  -
  -    my $modules = {
  -        warp_drive => 'My::Warp::Drive',
  -        load_warp_drive => 0,           # already online
  -        teleporter => 'My::Teleporter',
  -    };
  -
  -    my $warpmod = $object->module( warp_drive => $modules )
  -        || die $object->error();
  -
  -=head2 object($name, \%config)
  -
  -This method calls the C<module()> method to load the module associated 
  -with C<$name> and then instantiates an object by calling the C<new()>
  -method, forwards all remaining arguments.
  -
  -    my $warp_drive = $object->object( warp_drive => { warp => 2 } )
  -        || die $object->error();
  -
   =head2 error()
   
   The C<error()> method is used for error reporting.  When an object method
   fails for some reason, it calls the C<error()> method passing an argument
  -denoting the problem that occurred.
  +denoting the problem that occurred.  It then returns, passing back the 
  +return value from the error() method (typically C<undef>, but see the 
  +C<throw> option discussed below).
   
       sub engage {
           my $self = shift;
  @@ -935,7 +881,7 @@
       # calling package error() method
       my $object = My::Template::Module->new()
           || die My::Template::Module->error();
  -
  +    
       # accessing $ERROR package variable
       my $object = My::Template::Module->new()
           || die $My::Template::Module::ERROR;
  @@ -984,29 +930,55 @@
       # errors thrown as exceptions by default
       my $frob = My::Template::Frobulator->new();
   
  -If we want to disable the default behaviour defined by C<$THROW> then
  -we simply provide an explicit value for C<throw> as a constructor
  -option.  This can be set to C<undef> to provide the default
  -(i.e. non-throwing) behaviour, or can define a different exception
  -type.
  +If you want to disable the default behaviour defined by C<$THROW> then
  +provide an explicit value for C<throw> as a constructor option.  This
  +can be set to C<undef> to provide the default (i.e. non-throwing)
  +behaviour, or can define a different exception type.
   
       # errors return undef
       my $frob = My::Template::Frobulator->new( throw => undef );
  -
  +   
       # error thrown as 'frobless'
       my $frob = My::Template::Frobulator->new( throw => 'frobless' );
   
  +=head2 error_msg($message, @args)
  +
  +This is a wrapper around the C<error()> method.  It first looks for an
  +error message in a hash array defined in the C<$ERRORS> package
  +variable, looking in the object's own package and in the packages of
  +any of its base classes.  The first argument, C<$message> is used as
  +the key to index an error message from (one of) the hash array(s).
  +The corresponding value is expected to be a string or format which is
  +passed to C<sprintf()>, along with any additional arguments passed.
  +
  +    our $ERRORS = {
  +        missing => 'missing %s in template',
  +    }
  +    
  +    sub foo {
  +        my $self = shift;
  +    
  +        return $self->error_msg( missing => 'foo' )
  +            unless ... # some code
  +    }
  +
  +The above example showing the call to error_msg() is equivalent 
  +to the following code.
  +
  +        return $self->error('missing foo in template')
  +            unless ... # some code
  +
   =head2 throw()
   
  -This method throws an exception by calling die().  It can be called
  +This method throws an exception by calling C<die()>.  It can be called
   with one argument, which can either be a Template::Exception object
   (or subclass), or an error message which is upgraded into an exception
  -with the type set to 'undef' (that's the literal string "undef" rather
  -than the undefined value).
  +with the type set to C<'undef'> (that's the literal string C<"undef">
  +rather than the undefined value).
   
       # error message 
       $object->throw('an error has occurred');
  -
  +    
       # exception object
       $e = Template::Exception->new( engine => 'warp drive offline' );
       $object->throw($e);
  @@ -1064,12 +1036,12 @@
   
       sub disengage {
           my $self = shift;
  -
  +    
           $self->warning('warp drive already offline')
               unless $self->{ engaged };
  -
  +    
           # ...etc...
  -
  +    
           return 1;
       }
   
  @@ -1079,12 +1051,12 @@
   
       sub disengage {
           my $self = shift;
  -
  +    
           return $self->warning('warp drive already offline')
               unless $self->{ engaged };
  -
  +    
           # ...etc...
  -
  +    
           return 1;
       }
   
  @@ -1097,10 +1069,15 @@
   a reference to a list of current warnings.
   
       my $warnings = $object->warning();
  +    
       if (@$warnings) {
           warn "warning while disengaging warp drive: ", @$warnings;
       }
   
  +Please be aware that the C<warnings()> method isn't currently used by
  +any Template Toolkit objects and may be deprecated or modified in
  +future versions.
  +
   =head2 warnings()
   
   When called with arguments, this method calls the C<warning()> method once
  @@ -1108,7 +1085,7 @@
   
       # single call to warnings()
       $object->warnings('foo', 'bar', 'baz');
  -
  +    
       # multiple calls to warning()
       $object->warning('foo');
       $object->warning('bar');
  @@ -1123,11 +1100,37 @@
               $object->warnings();
       }
   
  +As with C<warning()>, this method isn't currently used and is subject
  +to change or deprecation in future versions.
  +
   =head2 decline($reason, $more_reasons, ...)
  +
  +The C<decline()> method is used to generate a return value and internal
  +state indicating that a method could not perform its task, but did not
  +incur an error.  This is typically used by methods which fetch and return
  +a resource, decline if it cannot be found, or raise an error if something
  +went seriously wrong.
   
  -This method concatentates all arguments into a single string, stores
  -it internally, and then returns C<undef>.  The string should indicate
  -a reason for declining a request (e.g. "frobulator template not found")
  +    sub get_thing {
  +        my ($self, $name) = @_;
  +    
  +        # hard error if database isn't connected
  +        my $db = $self->{ database }
  +            || return $self->error('no database')
  +    
  +        if ($thing = $database->fetch_thing($name)) {
  +            # return true value on success
  +            return $thing;
  +        }
  +        else {
  +            # soft decline if not found
  +            return $self->decline("thing not found: $name")
  +        }
  +    }
  +
  +The method concatentates all arguments into a single string, stores it
  +internally, and then returns C<undef>.  The string should indicate a
  +reason for declining a request (e.g. C<"thing not found: $name">)
   and can be subsequently retrieved via the C<declined()> method.
   
   =head2 declined()
  @@ -1135,6 +1138,10 @@
   Returns the reason for declining a request, as set by the most recent call
   to C<decline()>.
   
  +=head2 version()
  +
  +Returns the value of the C<$VERSION> package variable.
  +
   =head2 debug($msg1, $msg2, ...)
   
   At present this method simply prints all arguments to STDERR, prefixed 
  @@ -1181,7 +1188,7 @@
   
   =head1 VERSION
   
  -$Revision: 1.15 $
  +$Revision: 1.16 $
   
   =head1 COPYRIGHT