これは(うまくいけば!)以下を使用したOOベースの構成抽象化の簡単な例です。
NB。他のモジュールを使用することも、独自のモジュールをロールすることもできます。以下は一般的な例です。
RoomConfig.pm
package RoomConfig;
use Moose;
with 'MooseX::SimpleConfig';
has doors => (is => 'rw', isa => 'Int', required => 1);
has windows => (is => 'rw', isa => 'Int', default => sub {0});
1;
以上がOO構成クラスです。すべてがきちんと宣言されているので、構成オプションが利用可能で有効であることを明確に知っています。その自己文書化。
したがって、room
構成ファイルからを作成するには、次のようになります。
use RoomConfig;
my $box_room = RoomConfig->new_with_config( configfile => 'box_room.yaml' );
room
そのクラスなので、設定ファイルなしでをインスタンス化することもできます。
my $cupboard = RoomConfig->new( doors => 1 );
my $utility_room = RoomConfig->new( doors => 2 );
my $master_bedroom = RoomConfig->new(
doors => 1,
windows => 2, # dual aspect
);
また、これらの特定のモジュールを使用すると、次のような追加機能を利用できます。
# below throws exception because room must have a door!
my $room_with_no_door_or_window = RoomConfig->new;
したがって、私の構成は、構成ファイルから、または属性を設定することによって簡単に取得できます。
そして、さまざまなタイプの構成を拡張することで、さらに先に進むことができますrooms
。
BathRoomConfig.pm
package BathRoomConfig;
use Moose;
extends 'RoomConfig';
has loos => (is => 'rw', isa => 'Int', default => sub {0});
has sinks => (is => 'rw', isa => 'Int', default => sub {0});
has baths => (is => 'rw', isa => 'Int', default => sub {1});
1;
そして、この構成(bathroom.yaml)を使用した場合:
doors: 1
windows: 1
bath: 1
loos: 1
sinks: 2
次に、これを行うことができます:
use BathRoomConfig;
my $upstairs_bathroom = BathRoomConfig->new_with_config(
configfile => 'bathroom.yaml'
);
my $closet_room = BathRoomConfig->new_with_config(
configfile => 'bathroom.yaml',
baths => 0,
sinks => 1,
windows => 0,
);
$closet_room
設定ファイルと設定属性の両方を利用することに注意してください。
また、設定ファイルにdoors
必要なプロパティがない場合は、でエラーがスローされることに注意してくださいnew_with_config
。
そして最後に、定義された構成クラスを内省することが便利な場合があります。
use RoomConfig;
say "RoomConfig provides the following options:";
for my $attr (RoomConfig->meta->get_attribute_list) {
next if $attr eq 'configfile';
say '-> ', $attr;
}
Now there is nothing stopping you implementing most of this in a standard config package so at the end of the day its just horses for courses!
However the ease of managing all this is so much easier with OO and the features that these already written modules provide is big advantage especially in bigger projects.