我希望能够创建“幽灵”包和潜艇。我有一个包含如下条目的配置 (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 block 来解析 ini 文件,我们能够提供此 API:
if ( MyApp::Feature->user_login_rsa ) { ... }
问题是:是否可以创建以下 API:
if ( MyApp::Feature::User::Login::RSA ) { ... }
只有 MyApp::Feature?
小写,大写可以在配置文件中修改,这不是这里的问题。并明确表示,实现与配置分离,没有 MyApp::Feature::User::Login::RSA,永远不会。此功能的实现在于 f.e.在 MyApp::Humans 中。
我知道放置 MyApp::Feature::Foo::Bar 表明必须有这样的包。但是开发人员知道功能包管理功能切换的约定,他们不会有任何问题。我发现第一个示例(使用 enabled( $string ) 有点太复杂而难以阅读
if ( package::package->method ( string ) )
第二个更好:
if ( package::package->method )
第三个会更容易:
if ( package::package::package )
那么,是否可以在包级别模拟 AUTOLOAD?
您好, 罗布。
最佳答案
所以听起来您有一个要安装到命名空间中的多词键列表。
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
)};
关于perl - 在 Perl5 中实现功能切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9711601/