2011-11-28 167 views
3

我試圖做一個可擴展的系統,我可以編寫一個新模塊作爲處理程序。我想讓程序自動加載放入Handlers目錄中的任何新的.pm文件,並符合Moose :: Role接口。動態加載Perl模塊

我想知道是否有一個Perl模塊或更多穆斯認可的方式來自動執行此操作?這是我到目前爲止建立的,但它似乎有點冗長,並且必須有一個更簡單的方法來完成它。

handler.pl包含:

#!/usr/bin/perl 
      use Handler; 
    use Data::Dumper; 

    my $base_handler = Handler->new(); 
    $base_handler->load_modules('SysG/Handler'); 
    print Dumper($base_handler); 

Handler.pm包含:

package Handler; 
    use Moose; 

    has 'handlers' => (traits => ['Array'], handles => { add_handler => 'push' }); 

    sub load_modules { 
     my ($self,$dir) = @_; 

     push(@INC, $dir); 

     my @modules = find_modules_to_load($dir); 
     eval { 
      # Note that this sort is important. The processing order will be critically important. 
      # The sort implies the sort order 
      foreach my $module (sort @modules) { 
       (my $file = $module) =~ s|::|/|g; 
       print "About to load $file.pm for module $module\n" ; 
       require $file . '.pm'; 
       $module->import(); 
       my $obj = $module->new(); 
       $self->add_handler($obj); 
       1; 
      } 
     } or do { 
      my $error = [email protected]; 
      print "Error loading modules: $error" if $error; 
     }; 

    } 

    sub find_modules_to_load { 
     my ($dir) = @_; 
     my @files = glob("$dir/*.pm"); 
     my $namespace = $dir; 
     $namespace =~ s/\//::/g; 

     # Get the leaf name and add the System::Module namespace to it 
     my @modules = map { s/.*\/(.*).pm//g; "${namespace}::$1"; } @files; 
     die "ERROR: No classifier modules found in $dir\n" unless @modules; 
     return @modules; 
    } 

    1; 

然後我做了一個名爲SysG/Handler目錄,並增加了兩個.pm的文件,這通常會遵循一個木::角色(好像定義一個必須遵守的接口)。

SysG::Handler::0001_HandleX.pm存根包含:

package SysG::Handler::0001_HandleX; 
use Moose; 
1; 

SysG::Handler::0002_HandleX.pm存根包含:

package SysG::Handler::0002_HandleY; 
use Moose; 
1; 

將這個一起,數據::自卸車結果是:

$VAR1 = bless({ 
      'handlers' => [ 
          bless({}, 'SysG::Handler::0001_HandleX'), 
          bless({}, 'SysG::Handler::0002_HandleY') 
          ] 
      }, 'Handler'); 

所以,現在我重複我的原始問題:必須有一個更簡單的方法,或者一個模塊或一個駝鹿的方法自動加載特定目錄中的任何模塊。

任何駝鳥專家能夠幫助嗎?

+0

相關:http://stackoverflow.com/questions/4815432/what-is-the-best-option-for-building-a-plugin-system-for-a-moose-application – daxim

回答