MooseX::App::Cmd and your Command Line Apps

user-pic

Wiki Extras for this post

MooseX::App::Cmd is a really handy little module to add robustness and decoupling to your command line applications. It allows you to treat each command as a separate class, keeping your code tidy, and pretty re-usable.

Continue reading for an example of what I recently used it for....

This is the main class:

package App::MyApp;
use Moose;
use namespace::autoclean;
extends 'MooseX::App::Cmd';

1;

From here, you define your commands as such:

package App::MyApp::Command::get;
use Moose;
use namespace::autoclean;
extends 'MooseX::App::Cmd::Command';

has bucket => (
    is            => 'rw',
    isa           => 'Str',
    traits        => ['Getopt'],
    cmd_aliases   => "b",
    documentation => "bucket name to look up",
    required      => 1,
    lazy          => 1,
    default       => sub { croak "bucket name required" },
 );

has object => (
    is            => 'rw',
    isa           => 'Str',
    traits        => ['Getopt'],
    cmd_aliases   => "o",
    documentation => "object to download",
    required      => 1,
    lazy          => 1,
    default       => sub { croak  "object name required" },
); 

sub execute {
    my ( $self, $opt, $args ) = @_;

    my $container =
    ## this would be something an inherited class might 
    ## provide, a database handle, etc.
      $self->object_thingy->container( name => $self->bucket );
    my $object = $container->object( name => $self->object );
    $object->get_filename( $self->object )
      or die "Couldn't retrieve object: $!";

}
1;

Finally, the initialization script:

#!/usr/bin/env perl
use App::MyApp;
App::MyApp->run;

And it's invoked as such:

myapp.pl get filename.txt

This makes your code much much more modular, allowing you to focus on keeping your business logic in one place and inheriting from it anywhere (much like different views in the MVC concept).

No TrackBacks

TrackBack URL: http://www.catalyzed.org/mt/mt-tb.fcgi/82

Leave a comment

All comments are moderated. Spammers don't waste your time

Sponsored By


Ionzero: Rescue your dev project.

Following

Not following anyone

Note to spammers: all comments are moderated. Don't waste your time