diff options
-rw-r--r-- | lib/Youri/Utils.pm | 40 |
1 files changed, 24 insertions, 16 deletions
diff --git a/lib/Youri/Utils.pm b/lib/Youri/Utils.pm index a1e55f8..8a3927f 100644 --- a/lib/Youri/Utils.pm +++ b/lib/Youri/Utils.pm @@ -18,42 +18,50 @@ use warnings; our @EXPORT = qw( create_instance - load + load_class add2hash add2hash_ ); -=head2 create_instance(class => I<$class>, I<%options>) +=head2 create_instance($class, $config, $options) -Create an instance of a class at runtime. -I<$class> is the class name. -I<%options> are passed to the class constructor. -Returns the class instance. +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 ($expected_class, %options) = @_; + my ($interface, $config, $options) = @_; - die 'No expected class given' unless $expected_class; - die "No class given, expected derivated class from '$expected_class'" unless $options{class}; + croak 'No interface given' unless $interface; + croak 'No config given' unless $config; - # extract class from options - my $class = $options{class}; - delete $options{class}; + my $class = $config->{class}; + if (!$class) { + carp "No class given, can't load plugin"; + return; + } # ensure loaded - load($class); + load_class($class); # check interface - die "$class is not a $expected_class" unless $class->isa($expected_class); + if (!$class->isa($interface)) { + carp "$class is not a $interface"; + return; + } # instantiate no strict 'refs'; - return $class->new(%options); + + return $class->new( + $config->{options} ? %{$config->{options}} : (), + $options ? %{$options} : (), + ); } -sub load { +sub load_class { my ($class) = @_; $class .= '.pm'; |