私はMooseの初心者です。複数のプラグインをロードするオブジェクトを作成する必要があります。構造は次のようになります。
- 主なオブジェクト -> いくつかの一般的な機能
- プラグイン -> メイン オブジェクトの拡張機能
プラグインは、サーバー上の別のフォルダーにあります。メイン オブジェクトは、プラグインをロードして初期化し、オブジェクトをそれ自体に保存する必要があります。各プラグインの戻り値は、メイン オブジェクトを通過する必要があります。メイン オブジェクトは、呼び出し元の JSON 構造のすべての戻り値を変換する必要があるためです。
私は次のように呼びます:
my $main_obj = Main->new();
$main_obj->plugin('MainExtention')->get_title();
これが私のコード例です:
メイン オブジェクト:
package Main;
use Moose;
has 'plugins' => (
is => 'rw',
);
has 'title' => (
is => 'rw',
isa => 'Str',
reader => '_get_title',
);
# load plugins
sub _load_modules {
my $self = shift;
my $path = "/usr/local/apache/sites/.../Plugins";
push(@INC, $path);
my @modules = _find_modules_to_load($path);
eval {
my $plugins = {};
foreach my $module ( sort @modules) {
(my $file = $module) =~ s|::|/|g;
(my $modname = $module) =~ s/.*?(\w+$)/$1/;
require $file . '.pm';
my $obj = $module->new();
$plugins->{$modname} = $obj;
1;
}
$self->plugins($plugins);
} or do {
my $error = $@;
warn "Error loading modules: $error" if $error;
};
}
# read plugins
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;
return @modules;
}
sub BUILD {
my $self = shift;
$self->_load_modules();
}
sub get_title {
return 'main title'
}
1;
__PACKAGE__->meta->make_immutable;
ディレクトリ "/usr/local/apache/sites/.../Plugins" 内のプラグイン MainExtention:
package MainExtention;
use Moose;
has 'title' => (
is => 'rw',
isa => 'Str',
default => 'Default',
);
sub get_title {
return 'MainExtention Title';
}
1;
これは次のように機能します。
my $main = Main->new();
my $plugins = $main->plugins();
print $plugins->{'MainExtention'}->get_title();
しかし、これは私が持っているものではありません:)プラグインから直接ではなく、メインオブジェクトからプラグインの戻り値を取得します。誰にもアイデアはありますか?2 番目の質問: プラグインをロードする簡単な方法はありますか? どのように?