3

我希望能够创建“幽灵”包和潜艇。我有一个配置(ini)文件,其中包含如下条目:

[features]
sys.ext.latex = off
gui.super.duper.elastic = off
user.login.rsa = on

这个文件被解析了,以后开发者可以提出如下问题:

if ( MyApp::Feature->enabled ( 'user.login.rsa' ) { ... }

(整个想法基于 Martin Fowler 的 FeatureToggle http://martinfowler.com/bliki/FeatureToggle.html

使用 AUTOLOAD 来捕获 MyApp::Feature 中的调用,并使用 BEGIN 块来解析 ini 文件,我们能够提供此 API:

if ( MyApp::Feature->user_login_rsa ) { ... }

问题是:是否可以创建以下 API:

if ( MyApp::Feature::User::Login::RSA ) { ... }

只有 MyApp::Feature?

小写,大写可以在配置文件中修改,这不是这里的问题。并且说清楚,实现与配置是分离的,没有 MyApp::Feature::User::Login::RSA 并且永远不会。此功能的实现在于 MyApp::Humans 中的 fe。

我知道放置 MyApp::Feature::Foo::Bar 表明必须有这样的包。但是开发人员知道功能包管理功能切换的约定,他们对此没有任何问题。我发现第一个示例(使用 enabled( $string ) 有点太复杂,无法阅读

if ( package::package->method ( string ) )

第二个更好:

if ( package::package->method )

第三个会更容易:

if ( package::package::package )

那么,是否可以在包级别模拟 AUTOLOAD?

问候,罗布。


4

1 回答 1

4

因此,听起来您有一个要安装到命名空间中的多字键列表。

BEGIN {
    my %states = ( # the values that should be transformed
        on  => sub () {1},
        off => sub () {''},
    );
    sub install_config {
        my ($package, $config) = @_;
        for my $key (keys %$config) {
            my @parts = map ucfirst, split /\./, $key;
            my $name  = join '::' => $package, @parts;
            no strict 'refs';
            *{$name} = $states{$$config{$key}} # use a tranformed value
                    || sub () {$$config{$key}} # or the value itself
        }
    }
}

BEGIN {
    my %config = qw(
        sys.ext.latex            off
        gui.super.duper.elastic  off
        user.login.rsa           on
        some.other.config        other_value
    );
    install_config 'MyApp::Feature' => \%config;
}

say MyApp::Feature::Sys::Ext::Latex ? 'ON' : 'OFF';             # OFF
say MyApp::Feature::Gui::Super::Duper::Elastic ? 'ON' : 'OFF';  # OFF
say MyApp::Feature::User::Login::Rsa ? 'ON' : 'OFF';            # ON
say MyApp::Feature::Some::Other::Config;                        # other_value

此处安装的常量子例程将在适用时由 perl 内联。

您可以install_config通过将其放入包的导入功能使其更易于使用:

BEGIN {$INC{'Install/Config.pm'}++} # fool require

sub Install::Config::import {shift; goto &install_config}

use Install::Config 'MyApp::Feature' => {qw(
    sys.ext.latex            off
    gui.super.duper.elastic  off
    user.login.rsa           on
    some.other.config        other_value
)};
于 2012-03-15T00:58:33.713 回答