Subject: | [PATCH] Default _new_instance() implementation could be more useful |
Any additional arguments passed to the instance() method are forwarded
to the _new_instance() method, but the default implementation of that
does nothing with them.
In the Class-Singleton module the default implementation of
_new_instance() copies any additional arguments received into the new
object, so if you're happy to work with a simple hash reference based
object and you want to initialize attributes in it by passing arguments
to the instance() method then there is no need to provide your own
_new_instance() method to achieve that.
As an example, the following program prints "str = x":
package Foo;
use parent qw(Class::Singleton);
package main;
my $foo = Foo->instance(str => 'x');
print "str = ", ($foo->{str} // '<undef>'), "\n";
but if you use Apache::Singleton instead then it prints "str = <undef>".
It would be helpful if Apache-Singleton provided a similar default
implementation of _new_instance() to avoid needing to overload it in
cases like the above where no very specialized behaviour is required.
The attached patch does this by simply providing the same default
implementation as Class::Singleton.
Subject: | new.patch |
diff -ruN Apache-Singleton-0.11.orig/lib/Apache/Singleton.pm Apache-Singleton-0.11/lib/Apache/Singleton.pm
--- Apache-Singleton-0.11.orig/lib/Apache/Singleton.pm 2009-11-24 21:24:22.000000000 +0000
+++ Apache-Singleton-0.11/lib/Apache/Singleton.pm 2011-05-28 16:52:33.640625000 +0100
@@ -19,7 +19,9 @@
}
sub _new_instance {
- bless {}, shift;
+ my $class = shift;
+ my %args = @_ && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_;
+ bless { %args }, $class;
}
# Abstract methods, but compatible default