Hi,
This has happened to me enough tÆme that I think a module might be in
order:
I want to subclass an existing class,but I can't: the objects in this
class are created by an other existing class. I don't control the way that
class creates these objects.
Typically, when using an XML parser that creates a tree, I use a module. I
create an object ( "parser") in that module, which I can sub-class. But
then, during the parsing, the parser in turn creates the nodes in the
tree. I want to subclass those nodes, typically to add methods, and
sometimes data, to them.
I see 3 ways to do this:
- have the parser provide hooks to subclass the various types of nodes
that it creates which is not usually the case...
- take a good look at the parser, subclass it, and re-write ALL the
methods that create nodes, which seems like a lot of work for what I
want to do,
- mess with namespaces and add my own new methods to the original node
package(s), which I often do, but strikes me as not totally kosher
(and in any case it makes changing the constructor of the nodes a bit
awkward)
So I thought about it, looked around CPAN to figure out if I could find
something that would do this, did not find it, and set out to write it
myself.
I have a first, simple and quite clumsy version. I am looking for a good
module name, interface suggestion, and even implementation hints.
The first version is called Class::SubclassDeep, it offers a single
function (niark, niark! a procedural module to help those poor OO folks
lost in their class structure ;--):
subclass( class1 => "subclass1", class2 => "subclass2 (constructor)");
This replaces class1::new by a new method, that calls the original method,
but blesses the object as subclass1 before returning it. In the class2
case the difference is that the constructor is not called 'new' but
'constructor'.
Note that in this version the subclass is not allowed to have its own
constructor. I plan to change this by allowing a constructor, that will be
able to call the original constructor through a mean to be determined...
The original new (or constructor) method is saved in the symbol table as
'new_saved_by_subclassdeep', which is clumsy at best.
At the moment it is really a hack, but at least a hack hidden behind a
clean interface.
Does this makes sense? Did I miss anything?
The early version of the module is at
http://www.xmltwig/module/class-subclassdeep/
--
Michel Rodriguez
Perl & XML
http://www.xmltwig.com