1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
# $Id$
package Youri::Utils;
=head1 NAME
Youri::Utils - Youri shared functions
=head1 DESCRIPTION
This module implement some helper functions for all youri applications.
=cut
use base qw(Exporter);
use Carp;
use strict;
use warnings;
our @EXPORT = qw(
create_instance
load_class
add2hash
add2hash_
);
=head2 create_instance($class, $config, $options)
Create an instance from a plugin implementing given interface, using given
configuration and local options.
Returns a plugin instance, or undef if something went wrong.
=cut
sub create_instance {
my ($interface, $config, $options) = @_;
croak 'No interface given' unless $interface;
croak 'No config given' unless $config;
my $class = $config->{class};
if (!$class) {
carp "No class given, can't load plugin";
return;
}
# ensure loaded
load_class($class);
# check interface
if (!$class->isa($interface)) {
carp "$class is not a $interface";
return;
}
# instantiate
no strict 'refs';
return $class->new(
$config->{options} ? %{$config->{options}} : (),
$options ? %{$options} : (),
);
}
sub load_class {
my ($class) = @_;
$class .= '.pm';
$class =~ s/::/\//g;
require $class;
}
# structure helpers
sub add2hash {
my ($a, $b) = @_;
while (my ($k, $v) = each %{$b || {}}) {
$a->{$k} ||= $v;
}
return $a;
}
sub add2hash_ {
my ($a, $b) = @_;
while (my ($k, $v) = each %{$b || {}}) {
exists $a->{$k} or $a->{$k} = $v;
}
return $a;
}
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2002-2006, YOURI project
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
=cut
1;
|