Class::ConfigHash - Lazily turn multi-level hashes of configuration data in to objects with error catching and defaults
Lazily turn multi-level hashes of configuration data in to objects with error catching and defaults
my $config = Class::ConfigHash->_new({ database => { user => 'rodion', pass => 'bonaparte', options => { city => 'St Petersburg' }, }, }); $config->database->options->city; # St Petersburg # Dies: Can't find 'flags' at [/->database]. Options: [options; pass; user] $config->database->flags; # Won't die, returns undef $config->database->flags({ allow_undef => 1 }); # Won't die, returns 'foo' $config->database->flags({ default => 'foo' }); # Access the underlying structure $config->database({ raw => 1 })->{'user'} = 'raskolnikov';
Instantiates a new object. Preceeding underscore to stop collisions on hash keys. Accepts a hashref and an ArrayRef of strings, representing the depth that this hash is found at (defaults to ['/']).
['/']
You will probably never need to specify the depth yourself - instead:
my $config = Class::ConfigHash->_new( $hashref );
Every other method call tries to lookup the method name as a hashkey.
# Logically looks up ->{'configuration'}->{'database'}->{'host'} in wrapped hash my $host = $obj->configuration->database->host;
When a key doesn't exist a fatal error with helpful advice is thrown.
You can pass in some options as a hashref:
raw - Boolean - returns the item at the key, rather than attempting to wrap it
raw
allow_undef - Boolean - returns undef rather than throwing an error if key doesn't exist
allow_undef
default - Any value - returns this value rather than throwing an error if key doesn't exist.
default
eg:
# Don't get upset if host doesn't exist $obj->configuration->database->host({ allow_undef => 1 })
This is pretty similar to Class::Hash, except it's intended to be simply for configuration hashes, so there's no easy way to set values, there are defaults, and the error message gives you an overview of the different options you might want, and we autobox hashref children.
Module inspired by this patch to Dancer
Peter Sergeant pete@clueball.com - written while working for the excellent Net-A-Porter.
pete@clueball.com
To install Class::ConfigHash, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::ConfigHash
CPAN shell
perl -MCPAN -e shell install Class::ConfigHash
For more information on module installation, please visit the detailed CPAN module installation guide.