为Moose应用程序构建插件系统的最佳选择是什么? [英] What is the best option for building a plugin system for a Moose application?

查看:92
本文介绍了为Moose应用程序构建插件系统的最佳选择是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Perl和 Moose 编写一个可以通过插件扩展的应用.我知道有一些用于编写插件的Moose模块,我知道还有其他方法.

I want to write a app that can be extended via plugins, using Perl and Moose. I know there are a few Moose modules for writing plugins and I know there are other ways.

我有什么选择?我应该对他们了解些什么?在实施插件系统之前我应该​​考虑什么?

What are my options? and what should I know about them? any thing I should think about before implementing a plugin system?

推荐答案

有几种提供扩展性的方法;允许用户将角色应用于您的班级,或允许他们传入做有趣事情(委托)的小对象.与角色相比,代表的表现更好,但是要求您预先计划所有可扩展性.角色允许更多临时行为.

There are a few ways to provide extensibility; allow the user to apply roles to your class, or allow them to pass in small objects that do the interesting things (delegates). Delegates perform better than roles, but will require that you plan for all the extensibility up front. Roles allow more ad-hoc behaviors.

以下是两种采用每种方法的CPAN分布:

Here are two CPAN distributions that take each approach:

代表: AnyEvent :: Subprocess

角色: Devel :: REPL

插件角色是通过 MooseX :: Object :: Pluggable .

您可以根据自己的喜好来实现代表;该模式正在将一个类R的实例R传递给类C,然后将类C委托给类A.这是一个示例:

Delegates are implemented however you like; the pattern is passing an instance of a class A that does some role R to class C, and then class C delegates to A. Here's an example:

package Compare;
use Moose::Role;
requires 'compare';


package SpaceshipCompare;
use Moose;
with 'Compare';  

sub compare { my ($a, $b) = @_; return $a <=> $b }

package Sort;
use Moose;

has 'comparer' => (
    is       => 'ro',
    does     => 'Compare',
    handles  => 'Compare',
    required => 1,
);

sub my_sort {
    my ($self, @list) = @_;
    return sort { $self->compare($a, $b) } @list;
}

然后您可以这样使用:

my $sorter = Sort->new( comparer => SpaceshipCompare->new );
my @sorted = $sorter->my_sort("1one", "0", "43");

如果要更改Sort的工作方式,只需创建一个具有Compare角色的新类,然后将实例传递给Sort的构造函数即可.即时的灵活性!

If you want the way Sort works to change, you just create a new class that does the Compare role, and then pass an instance to Sort's constructor. Instant flexibility!

这篇关于为Moose应用程序构建插件系统的最佳选择是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆