return( $self->error( "Data provided to deserialise with $class is empty.") ) if( !defined( $opts->{data} ) || !length( $opts->{data} ) );
if( defined( $base64) )
{
my$decoded= $base64->[1]->( $opts->{data} );
return( &{"${class}\::thaw"}( $decoded) );
}
else
{
return( &{"${class}\::thaw"}( $opts->{data} ) );
}
}
elsif( exists( $opts->{io} ) )
{
return( $self->error( "File handle provided ($opts->{io}) is not an actual file handle to get data to deserialise.") ) if( Scalar::Util::reftype( $opts->{io} ) ne 'GLOB');
# Because in list context this would create a lit with one element undef()
# A bare return will return an empty list or an undef scalar
# return( undef() );
# return;
# As of 2019-10-13, Module::Generic version 0.6, we use this special package Module::Generic::Null to be returned in chain without perl causing the error that a method was called on an undefined value
# 2020-05-12: Added the no_return_null_object to instruct not to return a null object
# This is especially needed when an error is called from TIEHASH that returns a special object.
# A Null object would trigger a fatal perl segmentation fault
warn( "No error object provided and no previous error set either! It seems the previous method call returned a simple undef\n", $self->_get_stack_trace );
return( $self->error( "File handle provided ($opts->{io}) is not an actual file handle to serialise data to.") ) if( Scalar::Util::reftype( $opts->{io} ) ne 'GLOB');
if( defined( $base64) )
{
my$serialised= &{"${class}\::freeze"}( $data);
$serialised= $base64->[0]->( $serialised);
my$bytes= syswrite( $opts->{io}, $serialised);
return( $self->error( "Unable to write ", CORE::length( $serialised), " bytes of Storable serialised data to file handle '$opts->{io}': $!") ) if( !defined( $bytes) );
## If an error occurred, we report it to the caller and do not add it, since even if we did add it, it would be undef, because no object would have been created.
## And the caller needs to know there has been some errors
my$error= "Value provided for \"$field\" ($v) is not an anonymous subroutine (code). You can pass as argument something like \$self->curry::my_sub or something like sub { some_code_here; }";
# User removed the value by passing it an undefined value
if( !defined( $_[0] ) )
{
$data->{ $field} = undef();
}
# User pass an object
elsif( Scalar::Util::blessed( $_[0] ) )
{
my$o= shift( @_);
if( ref( $class) eq 'ARRAY')
{
my$ok= 0;
foreachmy$c( @$class)
{
if( $o->isa( $c) )
{
$ok++, last;
}
}
return( $self->error( "Object provided (", ref( $o), ") for $field does not match any of the possible classes: '", join( "', '", @$class), "'.") ) if( !$ok);
}
else
{
return( $self->error( "Object provided (", ref( $o), ") for $field is not a valid $class object") ) if( !$o->isa( "$class") );
}
$data->{ $field} = $o;
}
else
{
$class= $class->[0] if( ref( $class) eq 'ARRAY');
my$o= $self->_instantiate_object( $field, $class, @_) || do
{
if( $class->can( 'error') )
{
return( $self->pass_error( $class->error ) );
}
else
{
return( $self->error( "Unable to instantiate an object for class \"$class\" and values provided: '", join( "', '", @_), "'.") );
}
};
$data->{ $field} = $o;
}
}
else
{
$class= $class->[0] if( ref( $class) eq 'ARRAY');
# There is already an object, so we pass any argument to the existing object
# User removed the value by passing it an undefined value
if( !defined( $_[0] ) )
{
$data->{ $field} = undef();
}
# User pass an object
elsif( Scalar::Util::blessed( $_[0] ) )
{
my$o= shift( @_);
if( ref( $class) eq 'ARRAY')
{
my$ok= 0;
foreachmy$c( @$class)
{
if( $o->isa( $c) )
{
$ok++, last;
}
}
return( $self->error( "Object provided (", ref( $o), ") for $field does not match any of the possible classes: '", join( "', '", @$class), "'.") ) if( !$ok);
}
else
{
return( $self->error( "Object provided (", ref( $o), ") for $field is not a valid $class object") ) if( !$o->isa( "$class") );
}
$data->{ $field} = $o;
}
else
{
my$o= $self->_instantiate_object( $field, $class, @_) || do
{
if( $class->can( 'error') )
{
return( $self->pass_error( $class->error ) );
}
else
{
return( $self->error( "Unable to instantiate an object for class \"$class\" and values provided: '", join( "', '", @_), "'.") );
}
};
$data->{ $field} = $o;
}
}
else
{
my$o= $self->_instantiate_object( $field, $class, @_) || do
{
if( $class->can( 'error') )
{
return( $self->pass_error( $class->error ) );
}
else
{
return( $self->error( "Unable to instantiate an object for class \"$class\" with no value provided.") );
}
};
$data->{ $field} = $o;
}
}
# If nothing has been set for this field, ie no object, but we are called in chain, this will fail on purpose.
return( $self->error( "I was expecting an array ref, but instead got '$data_to_process'. _is_array returned: '", $self->_is_array( $data_to_process), "'") ) if( !$self->_is_array( $data_to_process) );
my$arr1= [];
foreachmy$ref( @$data_to_process)
{
return( $self->error( "I was expecting an embeded array ref, but instead got '$ref'.") ) if( ref( $ref) ne 'ARRAY');
my$arr= [];
for( my$i= 0; $i< scalar( @$ref); $i++ )
{
my$o;
if( defined( $ref->[$i] ) )
{
return( $self->error( "Parameter provided for adding object of class $class is not a reference.") ) if( !ref( $ref->[$i] ) );
if( Scalar::Util::blessed( $ref->[$i] ) )
{
return( $self->error( "Array offset $i contains an object from class ", $ref->[$i], ", but was expecting an object of class $class.") ) if( !$ref->[$i]->isa( $class) );
return( $self->error( "I was expecting an array ref, but instead got '$ref'. _is_array returned: '", $self->_is_array( $ref), "'") ) if( !$self->_is_array( $ref) );
my$arr= [];
for( my$i= 0; $i< scalar( @$ref); $i++ )
{
if( defined( $ref->[$i] ) )
{
# return( $self->error( "Array offset $i is not a reference. I was expecting an object of class $class or an hash reference to instantiate an object." ) ) if( !ref( $ref->[$i] ) );
if( Scalar::Util::blessed( $ref->[$i] ) )
{
return( $self->error( "Array offset $i contains an object from class ", $ref->[$i], ", but was expecting an object of class $class.") ) if( !$ref->[$i]->isa( $class) );
## Default value so that call to the caller's method like my_sub->length will not produce something like "Can't call method "length" on an undefined value"
## Also, this will make it possible to set default value in caller's object and we would turn it into array object.
# If the text contains libe breaks, we must stop the formatting before, or else there would be an ugly formatting on the entire screen following the line break
sub colour_open { return( shift->_set_get( 'colour_open', @_ ) ); }
PERL
# NOTE: parse()
colour_parse=> <<'PERL',
sub colour_parse
{
my $self = shift( @_ );
my $txt = join( '', @_ );
my $this = $self->_obj2h;
my $open = $this->{colour_open} || COLOUR_OPEN;
my $close = $this->{colour_close} || COLOUR_CLOSE;
no strict;
my $re = qr/
(?<all>
\Q$open\E(?!\/)(?<params>.*?)\Q$close\E
(?<content>
(?:
(?> [^$open$close]+ )
|
(?R)
)*+
)
\Q$open\E\/\Q$close\E
)
/x;
my $colour_re = qr/(?:(?:bright|light)[[:blank:]])?(?:[a-zA-Z]+(?:[[:blank:]]+[\w\-]+)?|rgb[a]?\([[:blank:]]*\d{1,3}[[:blank:]]*\,[[:blank:]]*\d{1,3}[[:blank:]]*\,[[:blank:]]*\d{1,3}[[:blank:]]*(?:\,[[:blank:]]*\d(?:\.\d)?)?[[:blank:]]*\))/;
my $style_re = qr/(?:bold|faint|italic|underline|blink|reverse|conceal|strike)/;
## Not undef, but rather empty string. Undef is associated with an error
return( '' );
}
return({ red => $red, green => $green, blue => $blue });
}
PERL
# NOTE: coloured()
coloured=> <<'PERL',
sub coloured
{
my $self = shift( @_ );
my $pref = shift( @_ );
my $text = CORE::join( '', @_ );
my $this = $self->_obj2h;
my( $style, $fg, $bg );
## my $colour_re = qr/(?:(?:bright|light)[[:blank:]])?[a-zA-Z]+/;
my $colour_re = qr/(?:(?:bright|light)[[:blank:]])?(?:[a-zA-Z]+(?:[[:blank:]]+[\w\-]+)?|rgb[a]?\([[:blank:]]*\d{1,3}[[:blank:]]*\,[[:blank:]]*\d{1,3}[[:blank:]]*\,[[:blank:]]*\d{1,3}[[:blank:]]*(?:\,[[:blank:]]*\d(?:\.\d)?)?[[:blank:]]*\))/;
my $style_re = qr/(?:bold|faint|italic|underline|blink|reverse|conceal|strike)/;
warn( "Warning only: _set_get_class was called from package $pack at line $line in file $file, but the type provided \"$type\" is unknown to us, so we are skipping this field \"$f\" in the creation of our virtual class.\n" . ( $type eq 'url' ? qq{Maybe you meant to use "uri" instead of "url" ?\n} : '' ) );
next;
}
my $func = $type2func->{ $type };
if( $type eq 'object' ||
$type eq 'scalar_or_object' ||
$type eq 'object_array_object' ||
$type eq 'object_array' )
{
if( !$info->{class} && !$info->{package} )
{
warn( "Warning only: _set_get_class was called from package $pack at line $line in file $file, and class \"$class\" field \"$f\" is to require an object, but no object class name was provided. Use the \"class\" or \"package\" property parameter. So we are skipping this field \"$f\" in the creation of our virtual class.\n" );
next;
}
my $this_class = $info->{class} || $info->{package};
warn( "Warning only: No dynamic class fields definition was provided for this field \"$f\". Skipping this field.\n" );
next;
}
elsif( ref( $this_def ) ne 'HASH' )
{
warn( "Warning only: I was expecting a fields definition hash reference for dynamic class field \"$f\", but instead got '$this_def'. Skipping this field.\n" );
# Of course, when an era starts and another era ends, it is during the same Gregorian year, so we use the new era for the year start although it is perfectly correct to use the nth year for the year end as well, but that would mean two eras for the same year, and although for humans it is ok, for computing it does not work.
# For example end of Meiji is in 1912 (45th year) which is also the first of the Taisho era
return( $self->error( "An error occurred while trying to create a DateTime object with the relative timestamp '$str' that translated into the unix time stamp '$ts': $e" ) );
}
}
elsif( lc( $str ) eq 'now' )
{
$dt = DateTime->now( time_zone => $tz );
return( $dt );
}
else
{
return( '' );
}
try
{
my $strp = DateTime::Format::Strptime->new( %$opt );
my $dt = $strp->parse_datetime( $str );
my $strp2 = $formatter->new( %$fmt );
# To enable the date string to be stringified to its original format
$dt->set_formatter( $strp2 ) if( $dt );
return( $dt );
}
catch( $e )
{
return( $self->error( "Error creating a DateTime object with the timestamp '$str': $e" ) );
}
}
PERL
# NOTE: _set_get_datetime()
_set_get_datetime=> <<'PERL',
sub _set_get_datetime : lvalue
{
my $self = shift( @_ );
my $field = shift( @_ );
my $this = $self->_obj2h;
my $data = $this->{_data_repo} ? $this->{ $this->{_data_repo} } : $this;
my $class = ref( $self ) || $self;
my $has_arg = 0;
my $arg;
if( want( qw( LVALUE ASSIGN ) ) )
{
( $arg ) = want( 'ASSIGN' );
$has_arg = 'assign';
}
else
{
if( @_ )
{
$arg = shift( @_ );
$has_arg++;
}
}
my $process = sub
{
my $time = shift( @_ );
my $now;
if( Scalar::Util::blessed( $time ) )
{
return( $self->error( "Object provided as value for $field, but this is not a DateTime or a Module::Generic::DateTime object" ) ) if( !$time->isa( 'DateTime' ) && !$time->isa( 'Module::Generic::DateTime' ) );
# Leave this commented out as we need it a little bit lower
my( $pkg, $file, $line) = caller();
my$sub= ( caller(1) )[3];
nooverloading;
nostrict 'refs';
if( $subeq 'Module::Generic::AUTOLOAD')
{
my$trace= $self->_get_stack_trace;
my$mesg= "Module::Generic::AUTOLOAD (called at line '$line') is looping for autoloadable method '$AUTOLOAD' and args '". join( "', '", @_) . "'. Trace is: ". $trace->as_string;
if( $MOD_PERL)
{
try
{
my$r= Apache2::RequestUtil->request;
$r->log->debug( $mesg);
}
catch( $e)
{
print( STDERR "Error trying to get the global Apache2::ApacheRec: $e\n");
sub age { return( shift->_set_get_number( 'age', @_ ) ); }
sub name { return( shift->_set_get_scalar( 'name', @_ ) ); }
sub uuid { return( shift->_set_get_uuid( 'uuid', @_ ) ); }
sub remote_addr { return( shift->_set_get_ip( 'remote_addr', @_ ) ); }
sub discount
{
return( shift->_set_get_class_array( 'discount',
{
amount => { type => 'number' },
discount => { type => 'object', class => 'My::Discount' },
}, @_ ) );
}
sub settings
{
return( shift->_set_get_class( 'settings',
{
# Will create a Module::Generic::Array array object of objects of class MY::Item
items => { type => 'object_array_object', class => 'My::Item' },
notify => { type => 'boolean' },
resumes_at => { type => 'datetime' },
timeout => { type => 'integer' },
customer => {
definition => {
billing_address => { package => "My::Address", type => "object" },
email => { type => "scalar" },
name => { type => "scalar" },
shipping_address => { package => "My::Address", type => "object" },
},
type => "class",
},
}, @_ ) );
}
=head1 VERSION
v0.28.3
=head1 DESCRIPTION
L<Module::Generic> as its name says it all, is a generic module to inherit from.
It is designed to provide a useful framework and speed up coding and debugging.
It contains standard and support methods that may be superseded by your module.
It also contains an AUTOLOAD transforming any hash object key into dynamic methods and also recognize the dynamic routine a la AutoLoader. The reason is that while C<AutoLoader> provides the user with a convenient AUTOLOAD, I wanted a way to also keep the functionnality of L<Module::Generic> AUTOLOAD that were not included in C<AutoLoader>. So the only solution was a merger.
=head1 METHODS
=head2 import
B<import>() is used for the AutoLoader mechanism and hence is not a public method.
It is just mentionned here for info only.
=head2 new
B<new> will create a new object for the package, pass any argument it might receive to the special standard routine B<init> that I<must> exist.
Then it returns what returns L</"init">.
To protect object inner content from sneaking by third party, you can declare the package global variable I<OBJECT_PERMS> and give it a Unix permission, but only 1 digit.
It will then work just like Unix permission. That is, if permission is 7, then only the module who generated the object may read/write content of the object. However, if you set 5, the, other may look into the content of the object, but may not modify it.
7, as you would have guessed, allow other to modify the content of an object.
If I<OBJECT_PERMS> is not defined, permissions system is not activated and hence anyone may access and possibly modify the content of your object.
If the module runs under mod_perl, and assuming you have set the variable C<GlobalRequest> in your Apache configuration, it is recognised and a clean up registered routine is declared to Apache to clean up the content of the object.
This methods calls L</init>, which does all the work of setting object properties and calling methods to that effect.
=head2 as_hash
This will recursively transform the object into an hash suitable to be encoded in json.
It does this by calling each method of the object and build an hash reference with the method name as the key and the method returned value as the value.
If the method returned value is an object, it will call its L</"as_hash"> method if it supports it.
It returns the hash reference built
=head2 clear
Alias for L</clear_error>
=head2 clear_error
Clear all error from the object and from the available global variable C<$ERROR>.
This is a handy method to use at the beginning of other methods of calling package, so the end user may do a test such as:
$obj->some_method( 'some arguments' );
die( $obj->error() ) if( $obj->error() );
## some_method() would then contain something like:
sub some_method
{
my $self = shift( @_ );
## Clear all previous error, so we may set our own later one eventually
$self->clear_error();
## ...
}
This way the end user may be sure that if C<$obj->error()> returns true something wrong has occured.
=head2 clone
Clone the current object if it is of type hash or array reference. It returns an error if the type is neither.
It returns the clone.
=head2 colour_close
The marker to be used to set the closing of a command line colour sequence.
Defaults to ">"
=head2 colour_closest
Provided with a colour, this returns the closest standard one supported by terminal.
A colour provided can be a colour name, or a 9 digits rgb value or an hexadecimal value
=head2 colour_format
Provided with a hash reference of parameters, this will return a string properly formatted to display colours on the command line.
Parameters are:
=over 4
=item I<text> or I<message>
This is the text to be formatted in colour.
=item I<bgcolour> or I<bgcolor> or I<bg_colour> or I<bg_color>
The value for the background colour.
=item I<colour> or I<color> or I<fg_colour> or I<fg_color> or I<fgcolour> or I<fgcolor>
The value for the foreground colour.
Valid value can be a colour name, an rgb value like C<255255255>, a rgb annotation like C<rgb(255, 255, 255)> or a rgba annotation like C<rgba(255,255,255,0.5)>
A colour can be preceded by the words C<light> or C<bright> to provide slightly lighter colour where supported.
Similarly, if an rgba value is provided, and the opacity is less than 1, this is equivalent to using the keyword C<light>
It returns the text properly formatted to be outputted in a terminal.
=item I<style>
The possible values are: I<bold>, I<italic>, I<underline>, I<blink>, I<reverse>, I<conceal>, I<strike>
=back
=head2 colour_open
The marker to be used to set the opening of a command line colour sequence.
Defaults to "<"
=head2 colour_parse
Provided with a string, this will parse the string for colour formatting. Formatting can be encapsulated in another formatting, and can be expressed in 2 different ways. For example:
$self->colour_parse( "And {style => 'i|b', color => green}what about{/} {style => 'blink', color => yellow}me{/} ?" );
would result with the words C<what about> in italic, bold and green colour and the word C<me> in yellow colour blinking (if supported).
Another way is:
$self->colour_parse( "And {bold light red on white}what about{/} {underline yellow}me too{/} ?" );
would return a string with the words C<what about> in light red bold text on a white background, and the words C<me too> in yellow with an underline.
$self->colour_parse( "Hello {bold red on white}everyone! This is {underline rgb(0,0,255)}embedded{/}{/} text..." );
would return a string with the words C<everyone! This is> in bold red characters on white background and the word C<embedded> in underline blue color
The idea for this syntax, not the code, is taken from L<Term::ANSIColor>
=head2 colour_to_rgb
Convert a human colour keyword like C<red>, C<green> into a rgb equivalent.
=head2 coloured
Provided with a colouring preference expressed as the first argument as string, and followed by 1 or more arguments that are concatenated to form the text string to format. For example:
print( $o->coloured( 'bold white on red', "Hello it's me!\n" ) );
my $ref = $self->deserialise( $hash_reference_of_options );
my $ref = $self->deserialise( $serialised_data, %hash_of_options );
my $ref = $self->deserialise( $serialised_data, $hash_reference_of_options );
This method deserialise data previously serialised by either L<CBOR|CBOR::XS>, L<Sereal> or L<Storable|Storable::Improved>.
It takes an hash or hash reference of options. You can also provide the data to deserialise as the first argument followed by an hash or hash reference of options.
The supported options are:
=over 4
=item C<base64>
Thise can be set to a true value like C<1>, or to your preferred base64 encoder/decoder, or to an array reference containing 2 code references, the first one for encoding and the second one for decoding.
If this is set simply to a true value, C<deserialise> will call L</_has_base64> to find out any installed base64 modules. Currently the ones supported are: L<Crypt::Misc> and L<MIME::Base64>. Of course, you need to have one of those modules installed first before it can be used.
If this option is set and no appropriate module could be found, C<deserialise> will return an error.
=item C<data>
Data to be deserialised.
=item C<file>
Provides a file path from which to read the serialised data.
=item C<io>
A filehandle to read the data to deserialise from. This option only works with L<Storable|Storable::Improved>
=item C<serialiser>
Specify the class name of the serialiser to use. Supported serialiser can either be C<CBOR> or L<CBOR::XS>, L<Sereal> and L<Storable|Storable::Improved>
If the serialiser is L<CBOR::XS> the following additional options are supported: C<max_depth>, C<max_size>, C<allow_unknown>, C<allow_sharing>, C<allow_cycles>, C<forbid_objects>, C<pack_strings>, C<text_keys>, C<text_strings>, C<validate_utf8>, C<filter>
See L<CBOR::XS> for detail on those options.
If the serialiser is L<Sereal>, the following additional options are supported: C<refuse_snappy>, C<refuse_objects>, C<no_bless_objects>, C<validate_utf8>, C<max_recursion_depth>, C<max_num_hash_entries>, C<max_num_array_entries>, C<max_string_length>, C<max_uncompressed_size>, C<incremental>, C<alias_smallint>, C<alias_varint_under>, C<use_undef>, C<set_readonly>, C<set_readonly_scalars>
See L<Sereal> for detail on those options.
=back
=head2 deserialize
Alias for L</deserialise>
=head2 debug
Set or get the debug level. This takes and return an integer.
Based on the value, L</"message"> will or will not print out messages. For example :
$self->debug( 2 );
Since C<2> used in L</"message"> is equal to the debug value, the debugging message is printed.
If the debug value is switched to 1, the message will be silenced.
=head2 deserialise
This method use a specified serialiser class and deserialise the given data either directly from a specified file or being provided, and returns the perl data.
The serialisers currently supported are: L<CBOR::Free>, L<CBOR::XS>, L<JSON>, L<Sereal> and L<Storable::Improved> (or the legacy L<Storable>). They are not required by L<Module::Generic>, so you must install them yourself. If the serialiser chosen is not installed, this will set an L<errr|Module::Generic/error> and return C<undef>.
This method takes some parameters as an hash or hash reference. It can then:
=over 4
=item * retrieve data directly from File
=item * retrieve data from a file handle (only with L<Storable>)
=item * Return the deserialised data
=back
The supported parameters are:
=over 4
=item * I<data>
String of data to deserialise.
=item * I<file>
String. A file path where to store the serialised data.
=item * I<io>
A file handle. This is used when the serialiser is L<Storable> to call its function L<Storable::Improved/store_fd> and L<Storable::Improved/fd_retrieve>
=item * I<lock>
Boolean. If true, this will lock the file before reading from it. This works only in conjonction with I<file> and the serialiser L<Storable::Improved>
=item * I<serialiser> or I<serializer>
A string being the class of the serialiser to use. This can be only either L<Sereal> or L<Storable> or L<Storable::Improved>
=back
Additionally the following options are supported and passed through directly to each serialiser:
=over 4
=item * L<CBOR::Free>: no option for deserialisation.
=item * L<Sereal::Decoder/decode> if the serialiser is L<Sereal>: C<alias_smallint>, C<alias_varint_under>, C<incremental>, C<max_num_array_entries>, C<max_num_hash_entries>, C<max_recursion_depth>, C<max_string_length>, C<max_uncompressed_size>, C<no_bless_objects>, C<refuse_objects>, C<refuse_snappy>, C<set_readonly>, C<set_readonly_scalars>, C<use_undef>, C<validate_utf8>
=item * L<Storable::Improved> / L<Storable>: no option available
=back
If an error occurs, this sets an L<error|Module::Generic/error> and return C<undef>
=head2 deserialize
Alias for L</deserialise>
=head2 dump
Provided with some data, this will return a string representation of the data formatted by L<Data::Printer>
=head2 dump_hex
Returns an hexadecimal dump of the data provided.
This requires the module L<Devel::Hexdump> and will return C<undef> and set an L</error> if not found.
=head2 dump_print
Provided with a file to write to and some data, this will format the string representation of the data using L<Data::Printer> and save it to the given file.
=head2 dumper
Provided with some data, and optionally an hash reference of parameters as last argument, this will create a string representation of the data using L<Data::Dumper> and return it.
This sets L<Data::Dumper> to be terse, to indent, to use C<qq> and optionally to not exceed a maximum I<depth> if it is provided in the argument hash reference.
=head2 dumpto
Alias for L</dumpto_dumper>
=head2 printer
Same as L</"dumper">, but using L<Data::Printer> to format the data.
=head2 dumpto_printer
Same as L</"dump_print"> above that is an alias of this method.
=head2 dumpto_dumper
Same as L</"dumpto_printer"> above, but using L<Data::Dumper>
=head2 errno
Sets or gets an error number.
=head2 error
Provided with a list of strings or an hash reference of parameters and this will set the current error issuing a L<Module::Generic::Exception> object, call L<perlfunc/warn>, or C<$r->warn> under Apache2 modperl, and returns undef() or an empty list in list context:
if( $some_condition )
{
return( $self->error( "Some error." ) );
}
Note that you do not have to worry about a trailing line feed sequence.
L</error> takes care of it.
The script calling your module could write calls to your module methods like this:
my $cust_name = $object->customer->name ||
die( "Got an error in file ", $object->error->file, " at line ", $object->error->line, ": ", $object->error->trace, "\n" );
# or simply:
my $cust_name = $object->customer->name ||
die( "Got an error: ", $object->error, "\n" );
If you want to use an hash reference instead, you can pass the following parameters. Any other parameters will be passed to the exception class.
=over 4
=item I<class>
The package name or class to use to instantiate the error object. By default, it will use L<Module::Generic::Exception> class or the one specified with the object property C<_exception_class>
$self->do_something_bad ||
return( $self->error({
code => 500,
message => "Oopsie",
class => "My::NoWayException",
}) );
my $exception = $self->error; # an My::NoWayException object
Note, however, that if the class specified cannot be loaded for some reason, L<Module::Generic/error> will die since this would be an error within another error.
=item I<message>
The error message.
=back
Note also that by calling L</error> it will not clear the current error. For that
you have to call L</clear_error> explicitly.
Also, when an error is set, the global variable I<ERROR> in the inheriting package is set accordingly. This is
especially usefull, when your initiating an object and that an error occured. At that
time, since the object could not be initiated, the end user can not use the object to
get the error message, and then can get it using the global module variable
I<ERROR>, for example:
my $obj = Some::Package->new ||
die( $Some::Package::ERROR, "\n" );
If the caller has disabled warnings using the pragma C<no warnings>, L</error> will
respect it and not call B<warn>. Calling B<warn> can also be silenced if the object has
a property I<quiet> set to true.
The error message can be split in multiple argument. L</error> will concatenate each argument to form a complete string. An argument can even be a reference to a sub routine and will get called to get the resulting string, unless the object property I<_msg_no_exec_sub> is set to false. This can switched off with the method L</"noexec">
If perl runs under Apache2 modperl, and an error handler is set with L</error_handler>, this will call the error handler with the error string.
If an Apache2 modperl log handler has been set, this will also be called to log the error.
If the object property I<fatal> is set to true, this will call die instead of L<perlfunc/"warn">.
Last, but not least since L</error> returns undef in scalar context or an empty list in list context, if the method that triggered the error is chained, it would normally generate a perl error that the following method cannot be called on an undefined value. To solve this, when an object is expected, L</error> returns a special object from module L<Module::Generic::Null> that will enable all the chained methods to be performed and return the error when requested to. For example:
my $o = My::Package->new;
my $total $o->get_customer(10)->products->total || die( $o->error, "\n" );
Assuming this method here C<get_customer> returns an error, the chaining will continue, but produce nothing and ultimately returns undef.
=head2 error_handler
Sets or gets a code reference that will be called to handle errors that have been triggered when calling L</error>
=head2 errors
Used by B<error>() to store the error sent to him for history.
It returns an array of all error that have occured in lsit context, and the last
error in scalar context.
=head2 errstr
Set/get the error string, period. It does not produce any warning like B<error> would do.
=head2 fatal
Boolean. If enabled, any error will call L<perlfunc/die> instead of returning L<perlfunc/undef> and setting an L<error|Module::Generic/error>.
Defaults to false.
You can enable it in your own package by initialising it in your own C<init> method like this:
sub init
{
my $self = shift( @_ );
$self->{fatal} = 1;
return( $self->SUPER::init( @_ ) );
}
=head2 get
Uset to get an object data key value:
$obj->set( 'verbose' => 1, 'debug' => 0 );
## ...
my $verbose = $obj->get( 'verbose' );
my @vals = $obj->get( qw( verbose debug ) );
print( $out "Verbose level is $vals[ 0 ] and debug level is $vals[ 1 ]\n" );
This is no more needed, as it has been more conveniently bypassed by the AUTOLOAD
generic routine with which you may say:
$obj->verbose( 1 );
$obj->debug( 0 );
## ...
my $verbose = $obj->verbose();
Much better, no?
=head2 init
This is the L</new> package object initializer. It is called by L</new>
and is used to set up any parameter provided in a hash like fashion:
my $obj My::Module->new( 'verbose' => 1, 'debug' => 0 );
You may want to superseed L</init> to have it suit your needs.
L</init> needs to returns the object it received in the first place or an error if
something went wrong, such as:
sub init
{
my $self = shift( @_ );
my $dbh = DB::Object->connect() ||
return( $self->error( "Unable to connect to database server." ) );
$self->{dbh} = $dbh;
return( $self );
}
In this example, using L</error> will set the global variable C<$ERROR> that will
contain the error, so user can say:
my $obj = My::Module->new() || die( $My::Module::ERROR );
If the global variable I<VERBOSE>, I<DEBUG>, I<VERSION> are defined in the module,
and that they do not exist as an object key, they will be set automatically and
accordingly to those global variable.
The supported data type of the object generated by the L</"new"> method may either be
a hash reference or a glob reference. Those supported data types may very well be
extended to an array reference in a near future.
When provided with an hash reference, and when object property I<_init_strict_use_sub> is set to true, L</init> will call each method corresponding to the key name and pass it the key value and it will set an error and skip it if the corresponding method does not exist. Otherwise, it calls each corresponding method and pass it whatever value was provided and check for that method return value. If the return value is L<perlfunc/undef> and the value provided is B<not> itself C<undef>, then it issues a warning and return the L</error> that is assumed having being set by that method.
Otherwise if the object property I<_init_strict> is set to true, it will check the object property matching the hash key for the default value type and set an error and return undef if it does not match. Foe example, L</"init"> in your module could be like this:
This would cause your script to die, because C<products> value is a string and not an array reference.
Otherwise, if none of those special object properties are set, the init will create an object property matching the key of the hash and set its value accordingly. For example :
The object would then contain the properties I<products>, I<first_name> and I<last_name> and can be accessed as methods, such as :
my $fname = $object->first_name;
You can also alter the way L</init> process the parameters received using the following properties you can set in your own C<init> method, for example:
sub init
{
my $self = shift( @_ );
# Set the order in which the parameters are processed, because some methods may rely on other methods' value
You can also specify a default exception class that will be used by L</error> to create exception object, by setting the object property C<_exception_class>:
sub init
{
my $self = shift( @_ );
$self->{name} = 'default_name';
# For any key-value pairs to be matched by a corresponding method
$self->{_init_strict_use_sub} = 1;
$self->{_exception_class} = 'My::Exception';
return( $self->SUPER::init( @_ ) );
}
=head2 log_handler
Provided a reference to a sub routine or an anonymous sub routine, this will set the handler that is called by L</"message">
It returns the current value set.
=head2 message
B<message>() is used to display verbose/debug output. It will display something to the extend that either I<verbose> or I<debug> are toggled on.
If so, all debugging message will be prepended by C< E<35>E<35> > by default or the prefix string specified with the I<prefix> option, to highlight the fact that this is a debugging message.
Addionally, if a number is provided as first argument to B<message>(), it will be treated as the minimum required level of debugness. So, if the current debug state level is not equal or superior to the one provided as first argument, the message will not be displayed.
For example:
## Set debugness to 3
$obj->debug( 3 );
## This message will not be printed
## This will be displayed
Now, why debug is used and not verbose level? Well, because mostly, the verbose level needs only to be true, that is equal to 1 to be efficient. You do not really need to have a verbose level greater than 1. However, the debug level usually may have various level.
Also, the text provided can be separated by comma, and even be a code reference, such as:
If the object has a property I<_msg_no_exec_sub> set to true, then a code reference will not be called and instead be added to the string as is. This can be done simply like this:
$self->noexec->message( 2, "I have found", "something weird here:", sub{ $self->dumper( $data ) } );
L</message> also takes an optional hash reference as the last parameter with the following recognised options:
=over 4
=item I<caller_info>
This is a boolean value, which is true by default.
When true, this will prepend the debug message with information about the caller of L</message>
=item I<level>
An integer. Debugging level.
=item I<message>
The text of the debugging message. This is optional since this can be provided as first or consecutive arguments like in a list as demonstrated in the example above. This allows you to do something like this:
or
=item I<no_encoding>
Boolean value. If true and when the debugging is set to be printed to a file, this will not set the binmode to C<utf-8>
=item I<prefix>
By default this is set to C<E<35>E<35>>. This value is used as the prefix used in debugging output.
=item I<type>
Type of debugging
=back
=head2 message_check
This is called by L</"message">
Provided with a list of arguments, this method will check if the first argument is an integer and find out if a debug message should be printed out or not. It returns the list of arguments as an array reference.
=head2 message_color
Alias for L</message_colour>
=head2 message_colour
This is the same as L</"message">, except this will check for colour formatting, which
L</"message"> does not do. For example:
$self->message_colour( 3, "And {bold light white on red}what about{/} {underline green}me again{/} ?" );
L</"message_colour"> can also be called as B<message_color>
See also L</"colour_format"> and L</"colour_parse">
=head2 message_frame
Return the optional hash reference of parameters, if any, that can be provided as the last argument to L</message>
=head2 messagef
This works like L<perlfunc/"sprintf">, so provided with a format and a list of arguments, this print out the message. For example :
Where 1 is the debug level set with L</"debug">
=head2 messagef_colour
This method is same as L</message_colour> and L<messagef> combined.
It enables to pass sprintf-like parameters while enabling colours.
=head2 message_log
This is called from L</"message">.
Provided with a message to log, this will check if L</"message_log_io"> returns a valid file handler, presumably to log file, and if so print the message to it.
If no file handle is set, this returns undef, other it returns the value from C<$io->print>
=head2 message_log_io
Set or get the message log file handle. If set, L</"message_log"> will use it to print messages received from L</"message">
If no argument is provided bu your module has a global variable C<LOG_DEBUG> set to true and global variable C<DEB_LOG> set presumably to the file path of a log file, then this attempts to open in write mode the log file.
It returns the current log file handle, if any.
=head2 new_array
Instantiate a new L<Module::Generic::Array> object. If any arguments are provided, it will pass it to L<Module::Generic::Array/new> and return the object.
=head2 new_datetime
Provided with some optional arguments and this will instantiate a new L<Module::Generic::DateTime> object, passing it whatever argument was provided.
Example:
my $dt = DateTime->now( time_zone => 'Asia/Tokyo' );
# Returns a new Module::Generic::DateTime object
my $d = $o->new_datetime( $dt );
# Returns a new Module::Generic::DateTime object with DateTime initiated automatically
# to now with time zone set by default to UTC
my $d = $o->new_datetime;
=head2 new_file
Instantiate a new L<Module::Generic::File> object. If any arguments are provided, it will pass it to L<Module::Generic::File/new> and return the object.
=head2 new_hash
Instantiate a new L<Module::Generic::Hash> object. If any arguments are provided, it will pass it to L<Module::Generic::Hash/new> and return the object.
=head2 new_json
This method tries to load L<JSON> and create a new object.
By default it enables the following L<JSON> object properties:
=over 4
=item L<JSON/allow_blessed>
=item L<JSON/allow_nonref>
=item L<JSON/convert_blessed>
=item L<JSON/relaxed>
=back
=head2 new_null
Returns a null value based on the expectations of the caller and thus without breaking the caller's call flow.
If the caller wants an hash reference, it returns an empty hash reference.
If the caller wants an array reference, it returns an empty array reference.
If the caller wants a code reference, it returns an anonymous subroutine that returns C<undef> or an empty list.
If the caller is calling another method right after, this means this is an object context and L</new_null> will instantiate a new L<Module::Generic::Null> object. If any arguments were provided to L</new_null>, they will be passed along to L<Module::Generic::Null/new> and the new object will be returned.
In any other context, C<undef> is returned or an empty list.
Without using L</new_null>, if you return simply undef, like:
my $val = $object->return_false->[0];
sub return_false{ return }
The above would trigger an error that the value returned by C<return_false> is not an array reference.
Instead of checking on the recipient end what kind of returned value was returned, the caller only need to check if it is defined or not, no matter the context in which it is called.
For example:
my $this = My::Object->new;
my $val = $this->call1;
# return undef)
# object context
$val = $this->call1->call_again;
# $val is undefined
# hash reference context
$val = $this->call1->fake->{name};
# $val is undefined
# array reference context
$val = $this->call1->fake->[0];
# $val is undefined
# code reference context
$val = $this->call1->fake->();
# $val is undefined
# scalar reference context
$val = ${$this->call1->fake};
# $val is undefined
# simple scalar
$val = $this->call1->fake;
# $val is undefined
package My::Object;
use parent qw( Module::Generic );
sub call1
{
return( shift->call2 );
}
sub call2 { return( shift->new_null ); }
sub call_again
{
my $self = shift( @_ );
print( "Got here in call_again\n" );
return( $self );
}
This technique is also used by L</error> to set an error object and return undef but still allow chaining beyond the error. See L</error> and L<Module::Generic::Exception> for more information.
=head2 new_number
Instantiate a new L<Module::Generic::Number> object. If any arguments are provided, it will pass it to L<Module::Generic::Number/new> and return the object.
=head2 new_scalar
Instantiate a new L<Module::Generic::Scalar> object. If any arguments are provided, it will pass it to L<Module::Generic::Scalar/new> and return the object.
=head2 new_tempdir
Returns a new temporary directory by calling L<Module::Generic::File/tempdir>
=head2 new_tempfile
Returns a new temporary directory by calling L<Module::Generic::File/tempfile>
=head2 noexec
Sets the module property I<_msg_no_exec_sub> to true, so that any call to L</"message"> whose arguments include a reference to a sub routine, will not try to execute the code. For example, imagine you have a sub routine such as:
sub hello
{
return( "Hello !" );
}
And in your code, you write:
If I<_msg_no_exec_sub> is set to false (by default), then the above would print out the following message:
Someone said Hello !
But if I<_msg_no_exec_sub> is set to true, then the same would rather produce the following :
Someone said CODE(0x7f9103801700)
=head2 pass_error
Provided with an error, typically a L<Module::Generic::Exception> object, but it could be anything as long as it is an object, hopefully an exception object, this will set the error value to the error provided, and without issuing any new warning nor creating a new L<Module::Generic::Exception> object.
It makes it possible to pass the error along so the caller can retrieve it later. This is typically used by a method calling another one in another module that produced an error. For example :
sub getCustomerInfo
{
my $self = shift( @_ );
# Maybe a LWP::UserAgent sub class?
my $client = $self->lwp_client_object;
my $res = $client->get( $remote_api_endpoint ) ||
return( $self->pass_error( $client->error ) );
}
Then :
my $client_info = $object->getCustomerInfo || die( $object->error, "\n" );
Which would return the http client error that has been passed along
=head2 quiet
Set or get the object property I<quiet> to true or false. If this is true, no warning will be issued when L</"error"> is called.
=head2 save
Provided with some data and a file path, or alternatively an hash reference of options with the properties I<data>, I<encoding> and I<file>, this will write to the given file the provided I<data> using the encoding I<encoding>.
This is designed to simplify the tedious task of write to files.
If it cannot open the file in write mode, or cannot print to it, this will set an error and return undef. Otherwise this returns the size of the file in bytes.
=head2 serialise
This method use a specified serialiser class and serialise the given data either by returning it or by saving it directly to a given file.
The serialisers currently supported are: L<CBOR::Free>, L<CBOR::XS>, L<JSON>, L<Sereal> and L<Storable::Improved> (or the legacy version L<Storable>). They are not required by L<Module::Generic>, so you must install them yourself. If the serialiser chosen is not installed, this will set an L<errr|Module::Generic/error> and return C<undef>.
This method takes some data and an optional hash or hash reference of parameters. It can then:
=over 4
=item * save data directly to File
=item * save data to a file handle (only with L<Storable::Improved> / L<Storable>)
=item * Return the serialised data
=back
The supported parameters are:
=over 4
=item * I<append>
Boolean. If true, the serialised data will be appended to the given file. This works only in conjonction with I<file>
=item * I<base64>
Thise can be set to a true value like C<1>, or to your preferred base64 encoder/decoder, or to an array reference containing 2 code references, the first one for encoding and the second one for decoding.
If this is set simply to a true value, C<serialise> will call L</_has_base64> to find out any installed base64 modules. Currently the ones supported are: L<Crypt::Misc> and L<MIME::Base64>. Of course, you need to have one of those modules installed first before it can be used.
If this option is set and no appropriate module could be found, C<serialise> will return an error.
=item * I<file>
String. A file path where to store the serialised data.
=item * I<io>
A file handle. This is used when the serialiser is L<Storable::Improved> / L<Storable> to call its function L<Storable::Improved/store_fd> and L<Storable::Improved/fd_retrieve>
=item * I<lock>
Boolean. If true, this will lock the file before writing to it. This works only in conjonction with I<file> and the serialiser L<Storable::Improved>
=item * I<serialiser> or I<serializer>
A string being the class of the serialiser to use. This can be only either L<Sereal> or L<Storable::Improved>
=back
Additionally the following options are supported and passed through directly for each serialiser:
=item * L<Sereal::Decoder/encode> if the serialiser is L<Sereal>: C<aliased_dedupe_strings>, C<canonical>, C<canonical_refs>, C<compress>, C<compress_level>, C<compress_threshold>, C<croak_on_bless>, C<dedupe_strings>, C<freeze_callbacks>, C<max_recursion_depth>, C<no_bless_objects>, C<no_shared_hashkeys>, C<protocol_version>, C<snappy>, C<snappy_incr>, C<snappy_threshold>, C<sort_keys>, C<stringify_unknown>, C<undef_unknown>, C<use_protocol_v1>, C<warn_unknown>
=item * L<Storable::Improved> / L<Storable>: no option available
=back
If an error occurs, this sets an L<error|Module::Generic/error> and return C<undef>
=head2 serialize
Alias for L</serialise>
=head2 set
B<set>() sets object inner data type and takes arguments in a hash like fashion:
$obj->set( 'verbose' => 1, 'debug' => 0 );
=head2 subclasses
Provided with a I<CLASS> value, this method try to guess all the existing sub classes of the provided I<CLASS>.
If I<CLASS> is not provided, the class into which was blessed the calling object will
be used instead.
It returns an array of subclasses in list context and a reference to an array of those
subclasses in scalar context.
If an error occured, undef is returned and an error is set accordingly. The latter can
be retrieved using the B<error> method.
=head2 true
Returns a C<true> variable from L<Module::Generic::Boolean>
=head2 false
Returns a C<false> variable from L<Module::Generic::Boolean>
=head2 verbose
Set or get the verbosity level with an integer.
=head2 will
This will try to find out if an object supports a given method call and returns the code reference to it or undef if none is found.
=head2 AUTOLOAD
The special B<AUTOLOAD>() routine is called by perl when no matching routine was found
in the module.
B<AUTOLOAD>() will then try hard to process the request.
For example, let's assue we have a routine B<foo>.
It will first, check if an equivalent entry of the routine name that was called exist in
the hash reference of the object. If there is and that more than one argument were
passed to this non existing routine, those arguments will be stored as a reference to an
array as a value of the key in the object. Otherwise the single argument will simply be stored
as the value of the key of the object.
Then, if called in list context, it will return a array if the value of the key entry was an array
reference, or a hash list if the value of the key entry was a hash reference, or finally the value
of the key entry.
If this non existing routine that was called is actually defined, the routine will be redeclared and
the arguments passed to it.
If this fails too, it will try to check for an AutoLoadable file in C<auto/PackageName/routine_name.al>
If the filed exists, it will be required, the routine name linked into the package name space and finally
called with the arguments.
If the require process failed or if the AutoLoadable routine file did not exist, B<AUTOLOAD>() will
check if the special routine B<EXTRA_AUTOLOAD>() exists in the module. If it does, it will call it and pass
it the arguments. Otherwise, B<AUTOLOAD> will die with a message explaining that the called routine did
not exist and could not be found in the current class.
=head1 SUPPORT METHODS
Those methods are designed to be called from the package inheriting from L<Module::Generic> to perform various function and speed up development.
=head2 __instantiate_object
Provided with an object property name, and a class/package name, this will attempt to load the module if it is not already loaded. It does so using L<Class::Load/"load_class">. Once loaded, it will init an object passing it the other arguments received. It returns the object instantiated upon success or undef and sets an L</"error">
This is a support method used by L</"_instantiate_object">
=head2 _has_base64
Provided with a value and this returns an array reference containing 2 code references: one for encoding and one for decoding.
Value provided can be a simple true value, such as C<1>, and then C<_has_base64> will check if L<Crypt::Misc> and L<MIME::Base64> are installed on the system and will use in priority L<MIME::Base64>
The value provided can also be an array reference already containing 2 code references, and in such case, that value is simply returned. Nothing more is done.
Finally, the value provided can be a module class name. C<_has_base64> knows only of L<Crypt::Misc> and L<MIME::Base64>, so if you want to use any other one, arrange yourself to pass to C<_has_base64> an array reference of 2 code references as explained above.
=head2 _instantiate_object
This does the same thing as L</"__instantiate_object"> and the purpose is for this method to be potentially superseded in your own module. In your own module, you would call L</"__instantiate_object">
=head2 _can
Provided with a value and a method name, and this will return true if the value provided is an object that L<UNIVERSAL/can> perform the method specified, or false otherwise.
Provided with arguments and this support method will return the arguments provided as an array reference irrespective of whether they were initially provided as array reference or a simple array.
For example:
my $array = $self->_get_args_as_array(qw( those are arguments ));
# returns an array reference containing: 'those', 'are', 'arguments'
my $array = $self->_get_args_as_array( [qw( those are arguments )] );
# same result as previous example
my $array = $self->_get_args_as_array(); # no args provided
# returns an empty array reference
=head2 _get_args_as_hash
Provided with arguments and this support method will return the arguments provided as hash reference irrespective of whether they were initially provided as hash reference or a simple hash.
In list context, this returns an hash reference and an array reference containing the order of the properties provided.
For example:
my $ref = $self->_get_args_as_hash( first => 'John', last => 'Doe' );
# returns hash reference { first => 'John', last => 'Doe' }
my $ref = $self->_get_args_as_hash({ first => 'John', last => 'Doe' });
# same result as previous example
my $ref = $self->_get_args_as_hash(); # no args provided
# returns an empty hash reference
my( $ref, $keys ) = $self->_get_args_as_hash( first => 'John', last => 'Doe' );
In the last example, C<$keys> is an L<array object|Module::Generic::Array> containing the list of properties passed an in the order they were provided, i.e. C<first> and C<last>. If the properties were provided as an hash reference, the C<$keys> returned will be the sorted list of properties, such as:
my( $ref, $keys ) = $self->_get_args_as_hash({ last => 'Doe', first => 'John' });
Here, C<$keys> will be sorted and contain the properties in their alphabetical order.
However, this will return empty:
my $ref = $self->_get_args_as_hash( { age => 42, city => 'Tokyo' }, some_other => 'parameter' );
This returns an empty hash reference, because although the first parameter is an hash reference, there is more than one parameter.
As of version v0.24.0, this utility method allows for more advanced use and permits embedding parameters among arguments, remove them from the list and return them.
C<$ref> is an hash reference that would contain C<debug> and C<@_> only contains C<foo bar baz>
You can also simply pass C<@_> as a reference to simply save memory.
Assuming C<@_> is C<foo bar baz 3 debug 4>
my $ref = $self->_get_args_as_hash( \@_ );
This would set C<$ref> to be an hash reference with keys C<foo baz debug>
=head2 _get_stack_trace
This will return a L<Devel::StackTrace> object initiated with the following options set:
=over 4
=item I<indent> 1
This will set an initial indent tab
=item I<skip_frames> 1
This is set to 1 so this very method is not included in the frames stack
=back
=head2 _implement_freeze_thaw
Provided with a list of package names and this method will implement in each of them the subroutines necessary to handle L<Storable::Improved> (or the legacy L<Storable>), L<CBOR|CBOR::XS> and L<Sereal> serialisation.
In effect, it will check that the subroutines C<FREEZE>, C<THAW>, C<STORABLE_freeze> and C<STORABLE_thaw> exists or sets up simple ones if they are not defined.
This works for packages that use hash-based objects. However, you need to make sure there is no specific package requirements, and if there is, you might need to customise those subroutines by yourself.
=head2 _is_a
Provided with an object and a package name and this will return true if the object is a blessed object from this package name (or a sub package of it), or false if not.
The value of this is to reduce the burden of having to check whether the object actually exists, i.e. is not null or undef, if it is an object and if it is from that class. This allows to do it in just one method call like this:
if( $self->_is_a( $obj, 'My::Package' ) )
{
# Do something
}
Of course, if you are sure the object is actually an object, then you can directly do:
if( $obj->isa( 'My::Package' ) )
{
# Do something
}
=head2 _is_class_loadable
Takes a module name and an optional version number and this will check if the module exist and can be loaded by looking at the C<@INC> and using L<version> to compare required version and existing version.
It returns true if the module can be loaded or false otherwise.
=head2 _is_class_loaded
Provided with a class/package name, this returns true if the module is already loaded or false otherwise.
It performs this test by checking if the module is already in C<%INC>.
=head2 _is_array
Provided with some data, this checks if the data is of type array, even if it is an object.
This uses L<Scalar::Util/"reftype"> to achieve that purpose. So for example, an object such as :
When checked with L</"_is_array"> this, would return true just like an ordinary array.
If you would use :
ref( $object );
It would rather return the module package name: C<My::Module>
=head2 _is_class_loadable
Provided with a package name, a.k.a. a class, and an optional version and this will endeavour to check if that class is installed and if a version is provided, if it is greater or equal to the version provided.
If the module is not already loaded and a version was provided, it uses L<Module::Metadata> to get that module version.
It returns true if the module can be loaded or false otherwise.
If an error occurred, it sets an L<error|/error> and returns C<undef>, so be sure to check whether the return value is defined.
=head2 _is_class_loaded
Provided with a package name, a.k.a. a class, and this returns true if the class has already been loaded or false otherwise.
If you are running under mod_perl, this method will use L<Apache2::Module/loaded> to find out, otherwise, it will simply check if the class exists in C<%INC>
=head2 _is_code
Provided with some value, possibly, undefined, and this returns true if it is a C<CODE>, such as a subroutine reference or an anonymous subroutine, or false otherwise.
=head2 _is_glob
Provided with some value, possibly, undefined, and this returns true if it is a filehandle, or false otherwise.
=head2 _is_hash
Same as L</"_is_array">, but for hash reference.
=head2 _is_integer
Returns true if the value provided is an integer, or false otherwise. A valid value includes an integer starting with C<+> or C<->
=head2 _is_ip
Returns true if the given IP has a syntax compliant with IPv4 or IPv6 including CIDR notation or not, false otherwise.
For this method to work, you need to have installed L<Regexp::Common::net>
=head2 _is_number
Returns true if the provided value looks like a number, false otherwise.
=head2 _is_object
Provided with some data, this checks if the data is an object. It uses L<Scalar::Util/"blessed"> to achieve that purpose.
=head2 _is_scalar
Provided with some data, this checks if the data is of type scalar reference, e.g. C<SCALAR(0x7fc0d3b7cea0)>, even if it is an object.
=head2 _is_uuid
Provided with a non-zero length value and this will check if it looks like a valid C<UUID>, i.e. a unique universal ID, and upon successful validation will set the value and return its representation as a L<Module::Generic::Scalar> object.
An empty string or C<undef> can be provided and will not be checked.
Provided with a class/package name, some optional list of semantics to import, and, as the last parameter, an optional hash reference of options and this will attempt to load the module. This uses L<perlfunc/use>, no external module.
Upon success, it returns the package name loaded.
It traps any error with an eval and return L<perlfunc/undef> if an error occurred and sets an L</error> accordingly.
Possible options are:
=over 4
=item I<caller>
The package name of the caller. If this is not provided, it will default to the value provided with L<perlfunc/caller>
=item I<no_import>
Set to a true value and this will prevent the loaded module from importing anything into your namespace.
This is the equivalent of doing:
use My::Module ();
=item I<version>
The minimum version for this class to load. This value is passed directly to L<perlfunc/use>
=back
=head2 _load_classes
This will load multiple classes by providing it an array reference of class name to load and an optional hash or hash reference of options, similar to those provided to L</_load_class>
If one of those classes failed to load, it will return immediately after setting an L</error>.
=head2 _lvalue
This provides a generic L<lvalue|perlsub> method that can be used both in assign context or lvalue context.
You only need to specify a setter and getter callback.
This takes an hash reference having either of the following properties:
=over 4
=item I<get>
A code reference that will be called, passing it the module object. It takes whatever value is returned and returns it to the caller.
=item I<set>
A code reference that will be called when values were provided either in assign or regular method context:
my $now = DateTime->now;
$o->datetime = $now;
# or
$o->datetime( $now );
=back
For example, in your module:
sub datetime : lvalue { return( shift->_lvalue({
set => sub
{
my( $self, $args ) = @_;
if( $self->_is_a( $args->[0] => 'DateTime' ) )
{
return( $self->{datetime} = shift( @$args ) );
}
else
{
return( $self->error( "Value provided is not a datetime." ) );
}
},
get => sub
{
my $self = shift( @_ );
my $dt = $self->{datetime};
return( $dt );
}
}, @_ ) ); }
# ^^^^
# Don't forget the @_ !
Be mindful that even if the setter callback returns C<undef> in case of an error, perl does not permit C<undef> to be returned from an lvalue method, and besides the return value in assign context is useless anyway:
my $dt = $o->datetime = DateTime->now;
If you want to check if assignment worked, you should opt to make error fatal and catch exceptions, such as:
$o->fatal(1);
try
{
$o->datetime = $not_a_datetime_object;
}
catch( $e )
{
die( "You provided a non DateTime object!: $e\n" );
}
or you can check if an error was set:
$o->datetime = $not_a_datetime_object;
die( "Did not work: ", $o->error ) if( $o->error );
=head2 _obj2h
This ensures the module object is an hash reference, such as when the module object is based on a file handle for example. This permits L<Module::Generic> to work no matter what is the underlying data type blessed into an object.
=head2 _parse_timestamp
Provided with a string representing a date or datetime, and this will try to parse it and return a L<DateTime> object. It will also create a L<DateTime::Format::Strptime> to preserve the original date/datetime string representation and assign it to the L<DateTime> object. So when the L<DateTime> object is stringified, it displays the same string that was originally parsed.
=head2 _set_get
sub name { return( shift->_set_get( 'name', @_ ) ); }
Provided with an object property name and some value and this will set or get that value for that property.
However, if the value stored is an array and is called in list context, it will return the array as a list and not the array reference. Same thing for an hash reference. It will return an hash in list context. In scalar context, it returns whatever the value is, such as array reference, hash reference or string, etc.
=head2 _set_get_array
Provided with an object property name and some data and this will store the data as an array reference.
It returns the current value stored, such as an array reference notwithstanding it is called in list or scalar context.
Example :
sub products { return( shift->_set_get_array( 'products', @_ ) ); }
=head2 _set_get_array_as_object
Provided with an object property name and some data and this will store the data as an object of L<Module::Generic::Array>
If this is called with no data set, an object is created with no data inside and returned
Example :
# In your module
sub products { return( shift->_set_get_array_as_object( 'products', @_ ) ); }
And using your method:
printf( "There are %d products\n", $object->products->length );
$object->products->push( $new_product );
Alternatively, you can pass an hash reference instead of an object property to provide callbacks that will be called upon addition or removal of value.
This hash reference can contain the following properties:
=over 4
=item field
The object property name
=item callbacks
An hash reference of operation type (C<add> or C<remove>) to callback subroutine name or code reference pairs.
=back
For example:
sub children { return( shift->set_get_array_as_object({
field => 'children',
callbacks =>
{
add => '_some_add_callback',
remove => 'som_remove_callback',
},
}), @_ ); }
The value of the callback can be either a subroutine name or a code reference.
=head2 _set_get_boolean
sub is_true { return( shift->_set_get_boolean( 'is_true', @_ ) ); }
Provided with an object property name and some data and this will store the data as a boolean value.
If the data provided is a L<JSON::PP::Boolean> or L<Module::Generic::Boolean> object, the data is stored as is.
If the data is a scalar reference, its referenced value is check and L<Module::Generic::Boolean/"true"> or L<Module::Generic::Boolean/"false"> is set accordingly.
If the data is a string with value of C<true> or C<val> L<Module::Generic::Boolean/"true"> or L<Module::Generic::Boolean/"false"> is set accordingly.
Otherwise the data provided is checked if it is a true value or not and L<Module::Generic::Boolean/"true"> or L<Module::Generic::Boolean/"false"> is set accordingly.
If no value is provided, and the object property has already been set, this performs the same checks as above and returns either a L<JSON::PP::Boolean> or a L<Module::Generic::Boolean> object.
Alternatively, you can pass an hash reference instead of an object property to provide callbacks that will be called upon addition or removal of value.
This hash reference can contain the following properties:
=over 4
=item field
The object property name
=item callbacks
An hash reference of operation type (C<add> or C<remove>) to callback subroutine name or code reference pairs.
=back
For example:
sub is_valid { return( shift->set_get_boolean({
field => 'is_valid',
callbacks =>
{
add => '_some_add_callback',
remove => 'som_remove_callback',
},
}), @_ ); }
The value of the callback can be either a subroutine name or a code reference.
=head2 __create_class
Provided with an object property name and an hash reference representing a dictionary and this will produce a dynamically created class/module.
If a property I<_class> exists in the dictionary, it will be used as the class/package name, otherwise a name will be derived from the calling object class and the object property name. For example, in your module :
sub products { return( 'products', shift->_set_get_class(
{
name => { type => 'scalar' },
customer => { type => 'object', class => 'My::Customer' },
orders => { type => 'array_as_object' },
active => { type => 'boolean' },
created => { type => 'datetime' },
metadata => { type => 'hash' },
stock => { type => 'number' },
url => { type => 'uri' },
}, @_ ) ); }
Then calling your module method B<products> such as :
Given an object property name, a dynamic class fiels definition hash (dictionary), and optional arguments, this special method will create perl packages on the fly by calling the support method L</"__create_class">
For example, consider the following:
#!/usr/local/bin/perl
BEGIN
{
use strict;
use Data::Dumper;
};
{
my $o = MyClass->new( debug => 3 );
$o->setup->age( 42 );
print( "Age is: ", $o->setup->age, "\n" );
print( "Setup object is: ", $o->setup, "\n" );
$o->setup->billing->interval( 'month' );
print( "Billing interval is: ", $o->setup->billing->interval, "\n" );
print( "Billing object is: ", $o->setup->billing, "\n" );
Setup object is: MyClass::Setup=HASH(0x7fa805abcb20)
Billing interval is: month
Billing object is: MyClass::Setup::Billing=HASH(0x7fa804ec3f40)
rgb: 255, 122, 100
The advantage of this over B<_set_get_hash_as_object> is that here one controls what fields / method are supported and with which data type.
=head2 _set_get_class_array
Provided with an object property name, a dictionary to create a dynamic class with L</"__create_class"> and an array reference of hash references and this will create an array of object, each one matching a set of data provided in the array reference. So for example, imagine you had a method such as below in your module :
sub products { return( shift->_set_get_class_array( 'products',
{
name => { type => 'scalar' },
customer => { type => 'object', class => 'My::Customer' },
orders => { type => 'array_as_object' },
active => { type => 'boolean' },
created => { type => 'datetime' },
metadata => { type => 'hash' },
stock => { type => 'number' },
url => { type => 'uri' },
}, @_ ) ); }
Then your script would call this method like this :
$object->products([
{ name => 'Cool product', customer => { first_name => 'John', last_name => 'Doe', email => 'john.doe@example.com' }, active => 1, stock => 10, created => '2020-04-12T07:10:30' },
{ name => 'Awesome tool', customer => { first_name => 'Mary', last_name => 'Donald', email => 'm.donald@example.com' }, active => 1, stock => 15, created => '2020-05-12T15:20:10' },
]);
And this would store an array reference containing 2 objects with the above data.
=head2 _set_get_code
Provided with an object property name and some code reference and this stores and retrieve the current value.
It returns under and set an error if the provided value is not a code reference.
=head2 _set_get_datetime
sub created_on { return( shift->_set_get_datetime( 'created_on', @_ ) ); }
Provided with an object property name and asome date or datetime string and this will attempt to parse it and save it as a L<DateTime> object.
If the data is a 10 digits integer, this will treat it as a unix timestamp.
Parsing also recognise special word such as C<now>
The created L<DateTime> object is associated a L<DateTime::Format::Strptime> object which enables the L<DateTime> object to be stringified as a unix timestamp using local time stamp, whatever it is.
Even if there is no value set, and this method is called in chain, it returns a L<Module::Generic::Null> whose purpose is to enable chaining without doing anything meaningful. For example, assuming the property I<created> of your object is not set yet, but in your script you call it like this:
$object->created->iso8601
Of course, the value of C<iso8601> will be empty since this is a fake method produced by L<Module::Generic::Null>. The return value of a method should always be checked.
=head2 _set_get_file
sub file { return( shift->_set_get_file( 'file', @_ ) ); }
Provided with an object property name and a file and this will store the given file as a L<Module::Generic::File> object.
It returns C<undef> and set an L<error|/error> if the provided value is not a proper file.
Note that the files does not need to exist and it can also be a directory or a symbolic link or any other file on the system.
=head2 _set_get_glob
sub handle { return( shift->_set_get_glob( 'handle', @_ ) ); }
Provided with an object property name and a glob (file handle) and this will store the given glob.
It returns C<undef> and set an L<error|/error> if the provided value is not a glob.
=head2 _set_get_hash
sub metadata { return( shift->_set_get_hash( 'metadata', @_ ) ); }
Provided with an object property name and an hash reference and this set the property name with this hash reference.
You can even pass it an associative array, and it will be saved as a hash reference, such as :
$object->metadata(
transaction_id => 123,
customer_id => 456
);
my $hash = $object->metadata;
=head2 _set_get_hash_as_mix_object
sub metadata { return( shift->_set_get_hash_as_mix_object( 'metadata', @_ ) ); }
Provided with an object property name, and an optional hash reference and this returns a L<Module::Generic::Hash> object, which allows to manipulate the hash just like any regular hash, but it provides on top object oriented method described in details in L<Module::Generic::Hash>.
This is different from L</_set_get_hash_as_object> below whose keys and values are accessed as dynamic methods and method arguments.
=head2 _set_get_hash_as_object
Provided with an object property name, an optional class name and an hash reference and this does the same as in L</"_set_get_hash">, except it will create a class/package dynamically with a method for each of the hash keys, so that you can call the hash keys as method.
Also it does this recursively while handling looping, in which case, it will reuse the object previously created, and also it takes care of adapting the hash key to a proper field name, so something like C<99more-options> would become C<more_options>. If the value itself is a hash, it processes it recursively transforming C<99more-options> to a proper package name C<MoreOptions> prepended by C<$class_name> provided as argument or whatever upper package was used in recursion processing.
For example in your module :
sub metadata { return( shift->_set_get_hash_as_object( 'metadata', @_ ) ); }
Then populating the data :
$object->metadata({
first_name => 'John',
last_name => 'Doe',
email => 'john.doe@example.com',
});
printf( "Customer name is %s\n", $object->metadata->last_name );
=head2 _set_get_ip
sub ip { return( shift->_set_get_ip( 'ip', @_ ) ); }
This helper method takes a value and check if it is a valid IP address using L</_is_ip>. If C<undef> or zero-byte value is provided, it will merely accept it, as it can be used to reset the value by the caller.
If a value is successfully set, it returns a L<Module::Generic::Scalar> object representing the string passed.
From there you can pass the result to L<Net::IP> in your own code, assuming you have that module installed.
=head2 _set_get_lvalue
This helper method makes it very easy to implement a L<perlsub/"Lvalue subroutines"> method.
print( "Level is: ", $obj->level, "\n" ); # Level is 4
print( "Is it an odd number: ", $obj->level->is_odd ? 'yes' : 'no', "\n" );
# Is it an od number: no
$obj->level++; # level is now 5
Alternatively, you can pass an hash reference instead of an object property to provide callbacks that will be called upon addition or removal of value.
This hash reference can contain the following properties:
=over 4
=item field
The object property name
=item callbacks
An hash reference of operation type (C<add> or C<remove>) to callback subroutine name or code reference pairs.
=back
For example:
sub length { return( shift->set_get_number({
field => 'length',
callbacks =>
{
add => '_some_add_callback',
remove => 'som_remove_callback',
},
}), @_ ); }
The value of the callback can be either a subroutine name or a code reference.
=head2 _set_get_number_or_object
Provided with an object property name and a number or an object and this call the value using L</"_set_get_number"> or L</"_set_get_object"> respectively
=head2 _set_get_object
Provided with an object property name, a class/package name and some data and this will initiate a new object of the given class passing it the data.
If you pass an undefined value, it will set the property as undefined, removing whatever was set before.
You can also provide an existing object of the given class. L</"_set_get_object"> will check the object provided does belong to the specified class or it will set an error and return undef.
It returns the object currently set, if any.
=head2 _set_get_object_lvalue
Same as L</_set_get_object_without_init> but with the possibility of setting the object value as an lvalue method:
$o->my_property = $my_object;
=head2 _set_get_object_without_init
Sets or gets an object, but countrary to L</_set_get_object> this method will not try to instantiate the object.
=head2 _set_get_object_array2
Provided with an object property name, a class/package name and some array reference itself containing array references each containing hash references or objects, and this will create an array of array of objects.
=head2 _set_get_object_array
Provided with an object property name and a class/package name and similar to L</"_set_get_object_array2"> this will create an array reference of objects.
=head2 _set_get_object_array_object
Provided with an object property name, a class/package name and some data and this will create an array of object similar to L</"_set_get_object_array">, except the array produced is a L<Module::Generic::Array>
=head2 _set_get_object_variant
Provided with an object property name, a class/package name and some data, and depending whether the data provided is an hash reference or an array reference, this will either instantiate an object for the given hash reference or an array of objects with the hash references in the given array.
This means the value stored for the object property will vary between an hash or array reference.
=head2 _set_get_scalar
sub name { return( shift->_set_get_scalar( 'name', @_ ) ); }
Provided with an object property name, and a string, possibly a number or anything really and this will set the property value accordingly. Very straightforward.
It returns the currently value stored.
=head2 _set_get_scalar_as_object
Provided with an object property name, and a string or a scalar reference and this stores it as an object of L<Module::Generic::Scalar>
If there is already an object set for this property, the value provided will be assigned to it using L<Module::Generic::Scalar/"set">
If it is called and not value is set yet, this will instantiate a L<Module::Generic::Scalar> object with no value.
So a call to this method can safely be chained to access the L<Module::Generic::Scalar> methods. For example :
sub name { return( shift->_set_get_scalar_as_object( 'name', @_ ) ); }
Then, calling it :
$object->name( 'John Doe' );
Getting the value :
my $cust_name = $object->name;
print( "Nothing set yet.\n" ) if( !$cust_name->length );
Alternatively, you can pass an hash reference instead of an object property to provide callbacks that will be called upon addition or removal of value.
This hash reference can contain the following properties:
=over 4
=item field
The object property name
=item callbacks
An hash reference of operation type (C<add> or C<remove>) to callback subroutine name or code reference pairs.
=back
For example:
sub name { return( shift->set_get_scalar_as_object({
field => 'name',
callbacks =>
{
add => '_some_add_callback',
remove => 'som_remove_callback',
},
}), @_ ); }
The value of the callback can be either a subroutine name or a code reference.
=head2 _set_get_scalar_or_object
Provided with an object property name, and a class/package name and this stores the value as an object calling L</"_set_get_object"> if the value is an object of class I<class> or as a string calling L</"_set_get_scalar">
If no value has been set yet, this returns a L<Module::Generic::Null> object to enable chaining.
=head2 _set_get_uri
sub uri { return( shift->_set_get_uri( 'uri', @_ ) ); }
sub uri { return( shift->_set_get_uri( { field => 'uri', class => 'URI::Fast' }, @_ ) ); }
Provided with an object property name, and an uri and this creates an L<URI> object and sets the property value accordingly.
Alternatively, the property name can be an hash with the following properties:
=over 4
=item I<field>
The object property name
=item I<class>
The URI class to use. By default, L<URI>, but you could also use L<URI::Fast>, or other class of your choice.
=back
It accepts an L<URI> object (or any other URI class object), an uri or urn string, or an absolute path, i.e. a string starting with C</>.
It returns the current value, if any, so the return value could be undef, thus it cannot be chained. Maybe it should return a L<Module::Generic::Null> object ?
=head2 _set_get_uuid
Provided with an object property name, and an UUID (Universal Unique Identifier) and this stores it as an object of L<Module::Generic::Scalar>.
If an empty or undefined value is provided, it will be stored as is.
However, if there is no value and this method is called in object context, such as in chaining, this will return a special L<Module::Generic::Null> object that prevents perl error that whatever method follows was called on an undefined value.
=head2 _to_array_object
Provided with arguments or not, and this will return a L<Module::Generic::Array> object of those data.
my $array = $self->_to_array_object( qw( Hello world ) ); # Becomes an array object of 'Hello' and 'world'
my $array = $self->_to_array_object( [qw( Hello world )] ); # Becomes an array object of 'Hello' and 'world'
=head2 _warnings_is_enabled
Called with the class object or providing another class object as argument, and this returns true if warnings are enabled for the given class, false otherwise.
Example:
$self->_warnings_is_enabled();
# Providing another class object
$self->_warnings_is_enabled( $other_object );
=head2 _warnings_is_registered
Called with the class object or providing another class object as argument, and this returns true if warnings are registered for the given class, false otherwise.
This is useful, because calling C<warnings::enabled()> to check if warnings are enabled for a given class when that class has not registered for warnings using the pragma C<use warnings::register> will produce an error C<Unknown warnings category>.
Example:
$self->_warnings_is_registered();
# Providing another class object
$self->_warnings_is_registered( $other_object );
=head2 __dbh
if your module has the global variables C<DB_DSN>, this will create a database handler using L<DBI>
It will also use the following global variables in your module to set the database object: C<DB_RAISE_ERROR>, C<DB_AUTO_COMMIT>, C<DB_PRINT_ERROR>, C<DB_SHOW_ERROR_STATEMENT>, C<DB_CLIENT_ENCODING>, C<DB_SERVER_PREPARE>
If C<DB_SERVER_PREPARE> is provided and true, C<pg_server_prepare> will be set to true in the database handler.
It returns the database handler object.
=for Pod::Coverage _autoload_subs
=for Pod::Coverage _autoload_add_to_cache
=head2 DEBUG
Return the value of your global variable I<DEBUG>, if any.
=head2 VERBOSE
Return the value of your global variable I<VERBOSE>, if any.
=head1 ERROR & EXCEPTION HANDLING
This module has been developed on the idea that only the main part of the application should control the flow and trigger exit. Thus, this module and all the others in this distribution do not die, but rather set and L<error|Module::Generic/error> and return undef. So you should always check for the return value.
Error triggered are transformed into an L<Module::Generic::Exception> object, or any exception class that is specified by the object property C<_exception_class>. For example:
Those error objects can then be retrieved by calling L</error>
If, however, you wanted errors triggered to be fatal, you can set the object property C<fatal> to a true value and/or set your package global variable C<$FATAL_ERROR> to true. When L</error> is called with an error, it will L<perlfunc/die> with the error object rather than merely returning C<undef>. For example:
The modules in the L<Module::Generic> distribution all supports L<Storable::Improved> (or the legacy L<Storable>), L<Sereal> and L<CBOR|CBOR::XS> serialisation, by implementing the methods C<FREEZE>, C<THAW>, C<STORABLE_freeze>, C<STORABLE_thaw>
Even the IO modules like L<Module::Generic::File::IO> and L<Module::Generic::Scalar::IO> can be serialised and deserialised if the methods C<FREEZE> and C<THAW> are used. By design the methods C<STORABLE_freeze> and C<STORABLE_thaw> are not implemented in those modules because it would trigger a L<Storable> exception "Unexpected object type (8) in store_hook()". Instead it is strongly encouraged you use the improved L<Storable::Improved> which addresses and mitigate those issues.
For serialisation with L<Sereal>, make sure to instantiate the L<Sereal encoder|Sereal::Encoder> with the C<freeze_callbacks> option set to true, otherwise, C<Sereal> will not use the C<FREEZE> and C<THAW> methods.
See L<Sereal::Encoder/"FREEZE/THAW CALLBACK MECHANISM"> for more information.
For L<CBOR|CBOR::XS>, it is recommended to use the option C<allow_sharing> to enable the reuse of references, such as:
my $cbor = CBOR::XS->new->allow_sharing;
Also, if you use the option C<allow_tags> with L<JSON>, then all of those modules will work too, since this option enables support for the C<FREEZE> and C<THAW> methods.