The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Class::ConfigHash - Lazily turn multi-level hashes of configuration data in to objects with error catching and defaults

DESCRIPTION

Lazily turn multi-level hashes of configuration data in to objects with error catching and defaults

SYNOPSIS

 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';

METHODS

_new

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 );

Auto-created methods generated for each hash key

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

allow_undef - Boolean - returns undef rather than throwing an error if key doesn't exist

default - Any value - returns this value rather than throwing an error if key doesn't exist.

eg:

 # Don't get upset if host doesn't exist
 $obj->configuration->database->host({ allow_undef => 1 })

SEE ALSO

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

AUTHOR

Peter Sergeant pete@clueball.com - written while working for the excellent Net-A-Porter.