From: Yuval Kogman Date: Thu, 26 Jun 2008 09:47:08 +0000 (+0000) Subject: update FAQ on constructor stuff X-Git-Tag: 0_55~94 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=e760b278942dcd7c9edd731b9a6ef26375bdaec0;p=gitmo%2FMoose.git update FAQ on constructor stuff --- diff --git a/lib/Moose/Cookbook/FAQ.pod b/lib/Moose/Cookbook/FAQ.pod index 9f1092c..c33896c 100644 --- a/lib/Moose/Cookbook/FAQ.pod +++ b/lib/Moose/Cookbook/FAQ.pod @@ -101,13 +101,21 @@ bets. =head3 How do I make non-Moose constructors work with Moose? -Moose provides its own constructor, but it does it by making all -Moose-based classes inherit from L. When inheriting -from a non-Moose class, the inheritance chain to L -is broken. The simplest way to fix this is to simply explicitly -inherit from L yourself. However, this does not -always fix the issue of a constructor. Here is a basic example of -how this can be worked around: +Usually the correct approach to subclassing a non Moose class is +delegation. Moose makes this easy using the C keyword, +coercions, and C, so subclassing is often not the +ideal route. + +That said, the default Moose constructors is inherited from +L. When inheriting from a non-Moose class, the +inheritance chain to L is broken. The simplest way +to fix this is to simply explicitly inherit from L +yourself. + +However, this does not always fix the issue of actually calling the Moose +constructor. Fortunately L, the low level +constructor, accepts the special C<__INSTANCE__> parameter, allowing you to +instantiate your Moose attributes: package My::HTML::Template; use Moose; @@ -123,13 +131,17 @@ how this can be worked around: return $class->meta->new_object( # pass in the constructed object # using the special key __INSTANCE__ - __INSTANCE__ => $obj, @_ + __INSTANCE__ => $obj, + @_, # pass in the normal args ); } Of course, this only works if both your Moose class and the inherited non-Moose class use the same instance type (typically -HASH refs). +HASH refs). + +Note that this doesn't call C automatically, you must do that +yourself. Other techniques can be used as well, such as creating the object using C, but calling the inherited non-Moose @@ -292,4 +304,4 @@ L This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. -=cut \ No newline at end of file +=cut