Configuring Kelp for command line tools

Building a complex web app almost never goes without the need to write a handful of command line tools. Whether it's to alter the database schema, convert image files, or move records from one format to another, you know you'll have to create a bin directory and fill it up with CLTs.

The Perl Kelp web framework makes this task easy with its robust and flexible configuration module. The default config file lives in conf/config.pl and contains a Perl hash of configuration options. For example:

# conf/config.pl
{
    modules      => [qw/Template Logger JSON RDBO Reddis/],
    modules_init => {
        # module initializations here
    }
};

This tells the framework to load the above modules when the application starts. Those modules are necessary for the web app, both in development and deployment mode, but they would just bloat the command line tools. To solve this problem, we can create a CLI configuration that makes amendments to the main configuration:

# conf/cli.pl
{
    "-modules" => ['Logger'],
    middleware => []
};

This disables the loading of the Logger module, because it assumes that your CLTs don't need it. Notice the minus sign in font of the modules key. It tells the config to remove "Logger" from the array of modules. All other configuration keys remain the same. A plus sign, respectively, would add to the modules array. The above config also completely disables the loading of any middleware, assuming that your CLTs won't need it.

Now we can write our first command line tool:

#!/usr/bin/env perl
use MyApp;
my $app = MyApp->new( mode => 'cli' ); 

# Use $app->rdb, $app->redis, or whatever other modules you
# have loaded, but rest assured that your tool won't pollute the
# access log.

Another example: Say, you only need the database module. You don't need JSON or Redis, and you won't be producing any templates. Create another config file:

# conf/cli_db.pl
{
    modules => ['RDBO']        # Rose::DB::Object
}

... then in your cli ...

use MyApp;
my $app = MyApp->new( mode => 'cli_db' );

# Now you can use $self->rdb, but not $self->redis and the rest.

Important takeaways:

  • The Kelp Config module loads the hash from conf/config.pl first, then looks for the mode specific configuration and merges it.
  • Hashes merge, scalars overwrite scalars, arrays also overwrite arrays except for when the key has a "+" or "-" in front of it, in which case the elements are added or removed to the array.
  • There is nothing wrong in creating many different config files and using them in your command line tools. Your schema loads too slow? Create a config that disables it.

Leave a comment

About Stefan G.

user-pic Random