Catalyst & Config
I will show how I load config data with catalyst.
AIM
Load config data not only for the catalyst application(MyApp::Web) but also CLI , an another Catalyst Application(e.g.. MyApp::AdminWeb) , etc...
MyApp::Config
This is how I implement config class. there are 2 points. and after set up this way, you can use this class whereever you want. By the way, I am using Config::Multi which is just my choice , you can chose something else you prefere .
- using Class::Singleton
- using MyAPp::Utils instead of Catalyst::Utils
package MyApp::Config;
use strict;
use warnings;
use Config::Multi;
use MyApp::Utils;
use base 'Class::Singleton';
our $FILES ;
sub _new_instance {
my $cm = Config::Multi->new(
{
dir => MyApp::Utils::path_to('conf')->stringify ,
app_name => 'myapp' ,
extension => 'yml'
});
my $config = $cm->load();
$FILES = $cm->files;
return $config;
}
sub files {
return $FILES;
}
1;
MyApp::Utils
If I use Catalyst::Utils then the MyApp::Config has dependancy with Catalyst which I want to avoid it so I use this class instead.
package MyApp::Utils;
use warnings;
use strict;
use Path::Class::Dir;
use Path::Class::File;
use FindBin;
sub home {
return $ENV{MYAPP_HOME} || Path::Class::Dir->new( $FindBin::Bin, './../' );
}
sub path_to {
my ( @path ) = @_;
my $path = Path::Class::Dir->new( &home , @path );
warn $path;
if ( -d $path ) { return $path }
else { return Path::Class::File->new( &home, @path ) }
}
1;
MyApp::Plugin::Config
package MyApp::Plugin::Config;
use strict;
use warnings;
use MyApp::Config;
use NEXT;
our $VERSION ='0.02';
sub setup {
my $c = shift;
my $config = MyApp::Config->instance();
if( $c->debug ) {
my $files = MyApp::Config->files();
for my $file ( @{$files} ) {
$c->log->debug( 'Load Config ' . $file );
}
}
$c->config( $config ) ;
$c->NEXT::setup( @_ );
}
1;
MyApp::Web
package MyApp::Web;
use strict;
use warnings;
use Catalyst::Runtime '5.70';
use Catalyst qw/+MyApp::Plugin::Config/;
our $VERSION = '0.01';
__PACKAGE__->setup;
1;
conf/myapp_web.yml
---
name: Config Sample
MyApp::Web::Controller::Root
package MyApp::Web::Controller::Root;
use strict;
use warnings;
use base 'Catalyst::Controller';
__PACKAGE__->config->{namespace} = '';
sub default : Private {
my ( $self, $c ) = @_;
$c->response->body( $c->config->{name} );
}
sub end : ActionClass('RenderView') {}
1;
Conclusion
when I use Catalyst::Plugin::Config** I could not use the module from outside of catalyst
but with this implementation I can use MyApp::Config whereever I want! hehehe.
perl-mongers.org < same article in japanese.
Comments