From: Stevan Little Date: Sat, 5 May 2007 15:01:39 +0000 (+0000) Subject: foo X-Git-Tag: 0_22~6 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=b36c80765f7d9458421ca78aab21fb6b77e715d7;p=gitmo%2FMoose.git foo --- diff --git a/lib/Moose/Cookbook/FAQ.pod b/lib/Moose/Cookbook/FAQ.pod index dbc40ea..88f61e5 100644 --- a/lib/Moose/Cookbook/FAQ.pod +++ b/lib/Moose/Cookbook/FAQ.pod @@ -279,6 +279,13 @@ constraint check. Not yet, but soon. This option will likely be coming in the next release. +=head2 Roles + +=head3 How do I get Moose to call BUILD in all my composed roles? + +See L and specifically the B question in the B section. + =head1 AUTHOR Stevan Little Estevan@iinteractive.comE diff --git a/lib/Moose/Cookbook/WTF.pod b/lib/Moose/Cookbook/WTF.pod index aa84b02..57a56f9 100644 --- a/lib/Moose/Cookbook/WTF.pod +++ b/lib/Moose/Cookbook/WTF.pod @@ -127,6 +127,67 @@ compile time like this: See L. +=head2 Roles + +=head3 How come BUILD is not called for my composed roles? + +BUILD is never called in composed roles. The primary reason is that +roles are B order sensitive. Roles are composed in such a way +that the order of composition does not matter (for information on +the deeper theory of this read the original traits papers here +L). + +Because roles are essentially un-ordered, it would be impossible to +determine the order in which to execute the BUILD methods. + +As for alternate solutions, there are a couple. + +=over 4 + +=item * + +Using a combination of lazy and default in your attributes to +defer initialization (see the Binary Tree example in the cookbook +for a good example of lazy/default usage +L) + +=item * + +Use attibutes triggers, which fire after an attribute it set, to faciliate +initialization. These are described in the L docs and examples can be +found in the test suite. + +=back + +In general, roles should not I intialization, they should either +provide sane defaults or should be documented as needing specific +initialization. One such way to "document" this is to have a seperate +attribute initializer which is required for the role. Here is an example of +how to do this: + + package My::Role; + use Moose::Role; + + has 'height' => ( + is => 'rw', + isa => 'Int', + lazy => 1, + default => sub { + my $self = shift; + $self->init_height; + } + ); + + requires 'init_height'; + +In this example, the role will not compose successfully unless the class +provides a C method. + +If none of those solutions work, then it is possible that a role is not +the best tool for the job, and you really should be using classes. Or, at +the very least, you should reduce the amount of functionality in your role +so that it does not require initialization. + =head1 AUTHOR Stevan Little Estevan@iinteractive.comE